【发布时间】:2015-09-22 08:01:35
【问题描述】:
我的目标是构建一个日志解析器,它将复制我想要的关键字之间的选定行并将其写入文件。由于我必须在单个文件中的多个关键字之间进行搜索,因此我想编写一个函数并在我的脚本中多次使用它。
但是我无法通过以下脚本实现这一点并收到错误:
import re
def myfunc (infile ,outfile, search1 , search2):
fi = infile.readlines()
fo = open(outfile, 'w')
write1 = False
for line in fi:
if re.findall('search1' , str(line)):
write1 = True
elif re.findall('search2', str(line)):
write1 = False
elif write1:
fo.write(line)
fo.close()
fi.close()
return;
text_file = open(input("name of inputfile : "))
resultfile = input("name of outputfile : ")
search1 = "teen"
search2 = "eight"
myfunc (text_file , resultfile , search1 , search2)
我收到以下错误:
Traceback (most recent call last):
File "C:/Users/zoro/PycharmProjects/text-parsing/write selected test 2 sets.py", line 38, in <module>
myfunc (text_file , resultfile , search1 , search2)
File "C:/Users/zoro/PycharmProjects/text-parsing/write selected test 2 sets.py", line 28, in myfunc
fi.close()
AttributeError: 'list' object has no attribute 'close'
【问题讨论】:
-
Poke 展示了如何修复您的功能。您不需要为此使用正则表达式:您可以使用
if search1 in line:,这要快得多。此外,如果您想多次调用该函数并将所有结果保存到同一个输出文件,那么您需要以'a'追加模式而不是'w'写入模式打开文件。
标签: python parsing python-3.x text