【发布时间】:2020-12-11 07:17:14
【问题描述】:
我在这个站点和其他站点上查看了许多关于替换字符的不同帖子,并且我之前已经完成了字符串替换。然而,在这个特定的例子中,我遇到了一个意想不到的问题。我希望我只是遗漏了一些明显的东西......
我正在尝试用其 HTML 实体代码替换特殊字符列表。我已经尝试了几个版本,从纯文本替换(½ 到 ½)到最后一次迭代,使用字节编码字符串(建议 here)
我的代码的功能非常简单。我得到一个文件的内容:
with open(cur_file, 'r', encoding='utf-8') as file_handle:
file_contents = file_handle.read()
file_handle.close()
然后我调用我的“replacer()”函数:
good_text = replacer(file_contents)
replacer() 函数内容:
def replacer(text):
replace_chars = {
b'\xc2\xbd': '½', #½
b'\xe2\x80\x9c': '"', #“
b'\xe2\x80\x9d': '"', #”
b'\xe2\x80\x99': '´', #’
b'\xe2\x80\x93': '—', #–
b'\xc2\xa9': '©' #©
}
for k, v in replace_chars.items():
good_text = text.replace(k.decode('utf-8'), v)
print('replacing ' + k.decode('utf-8') + ' with ' + v)
return good_text
然后我将新文本保存回文件中:
with open(cur_file, 'w', encoding='utf-8') as file_handle:
file_handle.write(good_text)
file_handle.close()
print('Done!')
在控制台中,我运行它并得到:
replacing ½ with ½
replacing “ with "
replacing ” with "
replacing ’ with ´
replacing – with —
replacing © with ©
Done!
这符合预期。但是,我要替换其中的字符串的文件具有以下内容:
replace_chars = {
'½': '½',
'“': '"',
'”': '"',
'’': '´',
'–': '—',
'©': '©'
我希望文件不包含½ 或第一列中的其他字符,而是类似于'©': '©'
【问题讨论】: