我試圖逐行讀取文件。如果在字典中找到,我想用值替換鍵值並將內容寫入新文件。這裏的邏輯:在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'的內容。如果你自己沒有發現任何可疑的東西,請將它們張貼在這裏。 –