【发布时间】:2019-01-04 06:52:03
【问题描述】:
这可能听起来平淡无奇,但确实很痛苦。 所以我编写了解析行的代码。 .txt 文件有一行与我的 re.match 匹配,另一行不匹配。
cat file.txt
00.00.00 : Blabla
x
在这种情况下,我会检查第一个字母“x”。
def parser():
path = "file.txt"
with open (path, 'r+') as file:
msg = {}
list = []
start = 0
lines = file.readlines()
for i in range (0,len(lines)):
line = lines[i]
if re.match('MY RULES', line) is not None:
field['date'] = line[:8]
msg['msg'] = line[start + 2:]
print msg
if line.startswith('x'):
msg['msg'] += line
list.append(msg)
print chat
输出 2 行
{'date': '0.0.00', 'msg': 'BlaBla'}
{'msg': 'x'}
问题是我不能将第二个 dict message['msg'] 附加到最后一条消息,如果以“x”开头。
预期的输出是:
{'date': '0.0.00', 'msg': 'BlaBlax'}
我尝试使用变体来更改最后附加的聊天:
else:
list[len(list) - 1]['msg'] += + line
但后来我得到了错误: IndexError: 列表索引超出范围
我也尝试使用 next(infile) 来预测下一行,但它每隔一行输出一次。
你会如何欺骗一个嵌套循环来附加一个 dict 条目?
干杯
【问题讨论】:
-
请修正缩进。目前,只有在匹配成功时才能处理带有“x”的行。这与您的预期结果不符。
-
也许 ` 如果 re.match('MY RULES', line) 不是 None:` 这不会让它通过添加
xasmsg来传递到行中 -
你总是有一对
(date, message)吗?在这种情况下,您可以阅读整个文件并执行str.split(':') -
@guidot:这就是重点。如果我在同一级别缩进 f,它将输出 msg['msg'] 作为单个值。前任。 {'date': '0.0.00', 'msg': 'BlaBla'} {'msg': 'x'} ------- 我想将它附加到之前匹配的字典中。
-
@harshil9968:评论“不是无”会影响结果。
标签: python list loops dictionary append