import codecs
with codecs.open('text_file.txt', 'r', encoding='utf-8') as file:
text = file.read()
with codecs.open('replacements_file.txt', 'r', encoding='utf-8') as file:
replacements = file.read().splitlines()
keywords = ["=="]
replaced_text = text
for i in range(len(keywords)):
count = 0
replaced_text = replaced_text.replace(keywords[i], lambda match: replacements[i] if count == match.start() else match.group(0), -1)
count += len(replacements[i])
with codecs.open('output_file.txt', 'w', encoding='utf-8') as file:
file.write(str(replaced_text))
运行时报错:
Traceback (most recent call last):
File "work.py", line 14, in <module>
replaced_text = replaced_text.replace(keywords[i], lambda match: replacements[i] if count == match.start() else match.group(0), -1)
TypeError: coercing to Unicode: need string or buffer, function found
import codecs
with codecs.open('text_file.txt', 'r', encoding='utf-8') as file:
text = file.read()
with codecs.open('replacements_file.txt', 'r', encoding='utf-8') as file:
replacements = file.read().splitlines()
keywords = "=="
replace_time = text.count(keywords)
result_text = text
for i in range(replace_time):
result_text = result_text.replace(keywords, replacements[i], 1)
with codecs.open('output_file.txt', 'w', encoding='utf-8') as file:
file.write(result_text)