我有一个正在搜索的文件,并将结果打印到一个文件中。我想知道是否有可能修改下面的代码以读取多个搜索词,例如打印任何包含"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这有可能做到吗?
发布于 2017-03-10 02:35:44
基于@new user代码(改进了一些错误),你可以这样做:
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()也许你会认为,最好打开文件一次,并检查每一行的一些术语。根据词条的数量,它将或多或少地效率,如果你愿意,可以研究它使用真正的大文件来检查执行时间,并了解更多。
发布于 2017-03-10 01:47:01
用空格分割你的词条。然后使用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() https://stackoverflow.com/questions/42701939
复制相似问题