简体   繁体   English

使用 python 中的 txt 文件中的数据进行计算

[英]Calculating with data from a txt file in python

Detailed:详细的:

I have a set of 200 or so values in a txt file and I want to select the first value b[0] and then go through the list from [1] to [199] and add them together.我在一个 txt 文件中有一组 200 个左右的值,我想 select 第一个值 b[0] 然后 go 通过从 [1] 到 [199] 的列表并将它们加在一起。

So, [0]+[1]所以,[0]+[1]

if that's not equal to a certain number, then it would go to the next term ie [0]+[2] etc etc until it's gone through every term.如果这不等于某个数字,那么它将 go 到下一个术语,即 [0]+[2] 等,直到它通过每个术语。 Once it's done that it will increase b[0] to b[1] and then goes through all the values again完成后,它将 b[0] 增加到 b[1],然后再次遍历所有值

Step by step:一步步:

  1. Select first number in list. Select 列表中的第一个数字。
  2. Add that number to the next number将该数字添加到下一个数字
  3. Check if that equals a number检查是否等于数字
  4. If it doesn't, go to next term and add to first term如果没有,go 到下一个学期并添加到第一个学期
  5. Iterate through these until you've gone through all terms/ found a value which adds to target value遍历这些,直到您完成所有条款/找到一个增加目标值的值
  6. If gone through all values, then go to the next term for the starting add value and continue如果遍历所有值,则 go 到下一项开始添加值并继续

I couldn't get it to work, if anyone can maybe provide a solution or give some advice?我无法让它工作,如果有人可以提供解决方案或提供一些建议吗? Much appreciated.非常感激。 I've tried looking at videos and other stack overflow problems but I still didn't get anywhere.我试过查看视频和其他堆栈溢出问题,但我仍然没有得到任何结果。 Maybe I missed something, let me know: Thank you!也许我错过了什么,让我知道:谢谢! :) :)

I've attempted it but gotten stuck.我已经尝试过了,但被卡住了。 This is my code so far:到目前为止,这是我的代码:

b = open("data.txt", "r")
data_file = open("data.txt", "r")

for i, line in enumerate(data_file):
    if (i+b)>2020 or (i+b)<2020:
        b=b+1
    else:
        print(i+b)
        print(i*b)

Error:错误:

Traceback (most recent call last):
  File "c:\Users\███\Desktop\ch1.py", line 11, in <module>
    if (i+b)>2020 or (i+b)<2020:
TypeError: unsupported operand type(s) for +: 'int' and '_io.TextIOWrapper'
PS C:\Users\███\Desktop>

Here are some things that you can fix.以下是您可以解决的一些问题。

You can't add the file object b to the integer i.您不能将文件 object b 添加到 integer i。 You have to convert the lines to int by using something like:您必须使用以下方法将行转换为 int:

integer_in_line = int(line.strip())

Also you have opened the same file twice in read mode with:您还以读取模式打开了两次相同的文件:

b = open("data.txt", "r")
data_file = open("data.txt", "r")

Opening it once is enough.打开一次就够了。

Make sure that you close the file after you used it:确保在使用后关闭文件:

data_file.close()

To compare each number in the list with each other number in the list you'll need to use a double for loop.要将列表中的每个数字与列表中的其他数字进行比较,您需要使用双 for 循环。 Maybe this works for you:也许这对你有用:

certain_number = 2020

data_file = open("data.txt", "r")
ints = [int(line.strip()) for line in data_file] # make a list of all integers in the file
for i, number_at_i in enumerate(ints): # loop over every integer in the list
    for j, number_at_j in enumerate(ints): # loop over every integer in the list
        if number_at_i + number_at_j == certain_number: # compare the integers to your certain number
            print(f"{number_at_i} + {number_at_j} = {certain_number}")

data_file.close()

I would read the file into an array and then convert it into ints before actually dealing with the problem.在实际处理问题之前,我会将文件读入数组,然后将其转换为整数。 files are messy and the less we have to deal with them the better文件很乱,我们处理的越少越好

with open("data.txt", "r") as data_file:
    lines = data_file.readlines() # reads the file into an array
    data_file.close
j = 0 # you could use a better much more terse solution but this is easy to understand
for i in lines: 
    lines[j] = int(i.strip().replace("\n", ""))
    j += 1

i, j = 0
for i in lines: # for every value of i we go through every value of j
    # so it would do x = [0] + [0] , [0] + [1] ... [1] + [0] .....
    for j in lines:
        x = j + i
        if x == 2020:
            print(i * j)

Your problem is the following: The variables b and data_file are not actually the text that you are hoping they are.您的问题如下:变量bdata_file实际上并不是您希望的文本。 You should read something about reading text files in python, there are many tutorials on that.您应该阅读一些有关阅读 python 中的文本文件的内容,有很多关于此的教程。

When you call open("path.txt", "r") , the open function returns a file object, not your text.当您调用open("path.txt", "r")时,打开的 function 返回文件 object,而不是您的文本。 If you want the text from the file, you should either call read or readlines .如果你想要文件中的文本,你应该调用readreadlines Also it is important to close your file after reading the content.阅读内容后关闭文件也很重要。

data_file = open("data.txt", "r") # b is a file object
text = data_file.read() # text is the actual text in the file in a single string
data_file.close()

Alternatively, you could also read the text into a list of strings, where each string represents one line in the file: lines = data_file.readlines() .或者,您也可以将文本读入字符串列表,其中每个字符串代表文件中的一行: lines = data_file.readlines()

I assume that your "data.txt" file contains one number per line, is that correct?我假设您的“data.txt”文件每行包含一个数字,对吗? In that case, your lines variable will be a list of the numbers, but they will be strings, not integers or floats.在这种情况下,您的 lines 变量将是一个数字列表,但它们将是字符串,而不是整数或浮点数。 Therefore, you can't simply use them to perform calculation.因此,您不能简单地使用它们来执行计算。 You would need to call int() on them.您需要对它们调用int()

Here is an example how to do it.这是一个如何做的例子。 I assumed that your textfile looks like this (with arbitary numbers):我假设您的文本文件看起来像这样(带有任意数字):

1
2
3
4
... 
file = open("data.txt", "r")
lines = file.readlines()
file.close()

# This creates a new list where the numbers are actual numbers and not strings
numbers = []
for line in lines:
   numbers.append(int(line))

target_number = 2020
starting_index = 0

found = False
for i in range(starting_index, len(numbers)):
    temp = numbers[i]
    for j in range(i + 1, len(numbers)):
        temp += numbers[j]
        if temp == target_number:
            print(f'Target number reached by adding nubmers from {i} to {j}')
            found = True
            break #This stops the inner loop.
    if found:
        break #This stops the outer loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM