-2
有人可以幫助我解決通過正則表達式解析文本文件的問題嗎?使用Python來執行代碼。我在下面的文本文件中有一個響應,我想解析並獲取值numvaluelist值。目前得到一個TypeError。使用Python解析文本文件時出現正則表達式問題
錯誤:字符串格式
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
非常感謝!多麼愚蠢的錯誤! –