多个搜索词和输出文件

2024-09-26 22:07:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,我正在搜索和打印结果到一个文件。我想知道是否有可能修改下面的代码来读取多个搜索词,即打印任何一行,其中有“test”或“hello”(用户将指定),但让Python为每个搜索词创建一个新的输出文件

也就是说,Ofile1将保存所有包含“test”的行 Ofile2将保留所有包含“hello”等的行

f = open('file3.txt') #input file

term = raw_input("What would you like to search for?") #takes an input to be searched

for line in f:
    if term in line:
        print (line) #print line of matched term

f.close() #close file

这有可能吗


Tags: 文件to代码用户intesthellofor
2条回答

用空格分隔术语。然后使用for循环遍历所有术语

例如:

terms = term.split(" ")
for t in terms:
    filename = t +"_output.txt"
    o = open(filename,'w')
    for line in f:
        if t in line:
            o.write(line) #print line of matched term
    o.close() 

基于@new user code(改进了一些错误),您可以这样做:

terms = raw_input("What would you like to search for?")
terms = terms.split(" ")
for term in terms:
    f = open('text.txt')
    filename = '{}_output.txt'.format(term)
    o = open(filename, 'w')
    for line in f:
        if term in line:
            o.write(line)
    o.close()
    f.close()

也许你可以认为最好打开文件一次,每行检查一些术语。根据术语的数量,它的效率会有所不同,如果您愿意,可以使用非常大的文件来检查执行时间并了解更多

相关问题 更多 >

    热门问题