Python 如何在文本文件中搜索数字

0 投票
5 回答
14315 浏览
提问于 2025-04-16 22:54

我有一个文本文件,里面的内容是逐行读取的,长得像这样:

3

3

67

46

67

3

46

每当程序遇到一个新数字时,它就会把这个数字写入一个文本文件。我打算这样做:先把第一个数字写入文件,然后看第二个数字,检查一下它是否已经在输出文件里。如果没有,就把这个数字写进去。如果已经有了,就跳过这一行,避免重复,然后继续看下一行。请问我该怎么做呢?

5 个回答

0

别这么做。用一个 set() 来记录你见过的所有数字。这样每个数字只会出现一次。

numbers = set()
for line in open("numberfile"):
    numbers.add(int(line.strip()))
open("outputfile", "w").write("\n".join(str(n) for n in numbers))

注意,这段代码是先把所有数字读进来,然后再一次性写出来。这样写出来的顺序会和原文件不一样(假设这些数字是整数,它们会按从小到大的顺序排列)。如果你不想这样,你也可以在读取的时候就写出来,但前提是这些数字还没有在集合里:

numbers = set()
with open("outfile", "w") as outfile:
    for line in open("numberfile"):
        number = int(line.strip())
        if number not in numbers:
            outfile.write(str(number) + "\n")
            numbers.add(number)
5

与其去查找你的输出文件,不如保持一份你已经写过的数字的集合,只写那些不在这个集合里的数字。

1

与其每次都去检查输出文件里有没有写过的数字,不如把这些信息保存在一个变量里(可以用一个 set 或者 list)。这样可以减少读取磁盘的次数。

要在文件中查找数字,你需要逐行读取文件,可以用 for line in open('input'): 这个循环来实现,其中 input 是你的文件名。在每次循环中,line 会包含输入文件中的一行,行末会有一个换行符 '\n'。

在每次循环中,你应该尝试把这一行的内容转换成数字,可以用 int() 函数来做到。如果这一行是空的或者不是数字,建议用 try 语句来保护自己。

在每次循环中,得到数字后,你需要检查这个数字是否已经写入过输出文件,可以通过查看已经写入数字的 set 来判断。如果这个数字还不在集合里,就把它加进去,并写入输出文件。

#!/usr/bin/env python                                                           
numbers = set() # create a set for storing numbers that were already written       
out = open('output', 'w') # open 'output' file for writing                      
for line in open('input'): # loop through each line of 'input' file             
    try:                                                                        
        i = int(line) # try to convert line to integer                          
    except ValueError:  # if conversion to integer fails display a warning         
        print "Warning: cannot convert to number string '%s'" % line.strip()       
        continue # skip to next line on error                                   
    if i not in numbers: # check if the number wasn't already added to the set  
        out.write('%d\n' % i) # write the number to the 'output' file followed by EOL
        numbers.add(i) # add number to the set to mark it as already added

这个例子假设你的 input 文件每行只包含一个数字。如果遇到空行或不正确的行,会在 stdout 上显示一个警告。

你也可以在上面的例子中使用 list,但效率可能会差一些。用 numbers = set() 的地方可以改成 numbers = [],而 numbers.add(i) 可以改成 numbers.append(i)。条件判断部分保持不变。

撰写回答