从包含混合 unicode 字符的文件中读取并替换字符串 (python)
这是文件内容:(
H\u00f6gskolan
Högskolan
注意:\u00f6
实际上是ö
)
我想将所有ö
字符替换为o,并将其保存到新文件中。 常规字符串替换无法按预期工作。
with open("test.txt", encoding="utf-8") as f:
content = f.read()
replacedContent = content.replace("ö", "o")
with open("testOutput.txt", "w", encoding="utf-8") as f:
f.write(replacedContent)
testOutput.txt 文件内容:
H\u00f6gskolan
Hogskolan
我发现了一个 类似问题,但其解决方案不起作用还有:
import codecs
with open("test.txt", encoding="utf-8") as f:
content = f.read()
content = codecs.decode(content, "unicode_escape")
replacedContent = content.replace("ö", "o")
with open("testOutput.txt", "w", encoding="utf-8") as f:
f.write(replacedContent)
testOutput.txt 文件内容:
Hogskolan
Högskolan
知道如何实现这一点吗?
Here is the file content:
H\u00f6gskolan
Högskolan
(Note: \u00f6
is actually ö
)
I want to replace all ö
characters with o
, and save it to a new file.
The regular string replace doesn't work as expected.
with open("test.txt", encoding="utf-8") as f:
content = f.read()
replacedContent = content.replace("ö", "o")
with open("testOutput.txt", "w", encoding="utf-8") as f:
f.write(replacedContent)
testOutput.txt file content:
H\u00f6gskolan
Hogskolan
I found a similar question but its solution didn't work as well:
import codecs
with open("test.txt", encoding="utf-8") as f:
content = f.read()
content = codecs.decode(content, "unicode_escape")
replacedContent = content.replace("ö", "o")
with open("testOutput.txt", "w", encoding="utf-8") as f:
f.write(replacedContent)
testOutput.txt file content:
Hogskolan
Högskolan
Any idea how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找不到任何已经处理您所请求内容的库函数,因此我只是使用正则表达式解析原始 unicode 签名并将其替换为实际值
I couldn't find any library function that already handles what you are requesting, so I just parse the raw unicode signatures with regex and replace them with their actual values