我试图逐行读取文件。如果在字典中找到,我想用值替换键值并将内容写入新文件。这里的逻辑:在Python中读取和写入文件
fout = open(output_file,"w+")
with open(input_file, 'r') as fin:
for line in fin:
for key in sorted(Db):
if re.match(key,line):
line = re.sub(key,Db[key],line) ## line 246
fout.write(line)
break
else:
fout.write(line)
每当我试图运行这个文件,我得到以下回溯:
Traceback (most recent call last):
File "final.py", line 246, in <module>
if re.match(key,line):
File "c:\Python33\lib\re.py", line 156, in match
return _compile(pattern, flags).match(string)
File "c:\Python33\lib\functools.py", line 258, in wrapper
result = user_function(*args, **kwds)
File "c:\Python33\lib\re.py", line 274, in _compile
return sre_compile.compile(pattern, flags)
File "c:\Python33\lib\sre_compile.py", line 493, in compile
p = sre_parse.parse(p, flags)
File "c:\Python33\lib\sre_parse.py", line 724, in parse
p = _parse_sub(source, pattern, 0)
File "c:\Python33\lib\sre_parse.py", line 347, in _parse_sub
itemsappend(_parse(source, state))
File "c:\Python33\lib\sre_parse.py", line 552, in _parse
raise error("nothing to repeat")
sre_constants.error: nothing to repeat
请让我知道如果我失去了一些东西。提前致谢。
感谢, 阿南德
看起来像一个糟糕的正则表达式模式。你应该检查'Db'的内容。如果你自己没有发现任何可疑的东西,请将它们张贴在这里。 –