通过Regex解析文本文件,有人可以帮我解决问题吗?使用Python执行代码。我在下面的文本文件中有一个回复,我想解析并获得 numvaluelist 值。目前正在获取TypeError。
错误:
lines = line_re.findall(data)
TypeError: expected string or buffer
字符串格式的文本文件(.txt)
historic_list {
id: "Text1(long) 11A"
startdate: 345453
numvaluelist: 0.123
datelist: 345453
}
historic_list {
id: "Text1(short) 11B"
startdate: 345453
numvaluelist: 0.456
datelist: 345453
}
historic_list {
id: "Text2(long) 11C"
startdate: 345453
numvaluelist: 1.789
datelist: 345453
}
datelist: 345453
}
time_statistics {
job_id: "123"
}
UrlPairList {
}
Python代码
f= open(".txt_file", "r")
data = f.readlines()
# print data
line_re = re.compile(r'\{[^\}]+\}')
value_re = re.compile(r"(\w+): ('[^']*'|\S+)")
results = []
lines = line_re.findall(data)
for line in lines:
data_line = dict()
values = re.findall(value_re, line)
for (name, value) in values:
if(value[-1] == '}'): value = value[:-1] # to handle "foo}" without space
if(value[:1] == "'"): value = value[1:-1] # strip quotes
data_line[name] = value
results.append(data_line)
print type(results)
final_results = []
for i in results:
for key, value in i.items():
if key == 'numvaluelist':
final_results.append(i['numvaluelist'])
print final_results
答案 0 :(得分:2)
问题不在于你的正则表达式。 readlines
返回一个列表,但re.findall
采用字符串或缓冲区。
你想要的是:
data = f.read()
将文件内容作为单个字符串返回。