【发布时间】:2018-08-08 04:05:27
【问题描述】:
我正在尝试打开一个文本文件,然后通读它,将某些字符串替换为存储在字典中的字符串。基于对Replacing words in text file using a dictionary 和How to search and replace text in a file using Python? 的回答
如:
# edit print line to print (line)
import fileinput
text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}
for line in fileinput.input(text, inplace=True):
line = line.rstrip()
for field in fields:
if field in line:
line = line.replace(field, fields[field])
print (line)
我的文件编码为utf-8。
当我运行它时,控制台显示此错误:
UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>
当添加:encoding = "utf8" 到 fileinput.FileInput() 时显示错误:
TypeError: __init__() got an unexpected keyword argument 'encoding'
当添加:openhook=fileinput.hook_encoded("utf8") 到 fileinput.FileInput() 时显示错误:
ValueError: FileInput cannot use an opening hook in inplace mode
我不想插入子代码'ignore' 忽略错误。
我有文件、字典并希望将字典中的值替换为 stdout 之类的文件。
utf-8中的源文件:
Plain text on the line in the file.
This is a greeting to the world.
Hello world!
Here's another plain text.
And here too!
我想用单词earth 替换单词world。
字典中:{"world": "earth"}
utf-8中的修改文件:
Plain text on the line in the file.
This is a greeting to the earth.
Hello earth!
Here's another plain text.
And here too!
【问题讨论】:
-
您使用的是 Python 2,而不是 Python 3。
-
我正在使用 Python 3。在 .py 顶部我有 # -- coding: utf-8 --。否则它将如何用 Python 3 编写?主要问题是一些较旧的问题和答案是用 Python 2 编写的。
-
啊,确实,我错了,Python 3 版本没有
encoding选项。我的错。 -
我猜你使用的是Windows?
-
是的。 Anaconda Spyder。
标签: python dictionary replace file-io runtime-error