从包含混合 unicode 字符的文件中读取并替换字符串 (python)

发布于 2025-01-12 04:15:06 字数 1015 浏览 0 评论 0原文

这是文件内容:(

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

物价感观 2025-01-19 04:15:06

我找不到任何已经处理您所请求内容的库函数,因此我只是使用正则表达式解析原始 unicode 签名并将其替换为实际值

import re


def convert_mixed(from_file, to_file):
    f = open(from_file, "r")
    content = f.read()
    f.close()
    for x in re.findall(r"\\u([\da-f]{4})", content):
        content = content.replace(f"\\u{x}", chr(int(x, 16)))

    f = open(to_file, "w")
    f.write(content.replace("ö", "o"))


convert_mixed("file.txt", "out.txt")

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

import re


def convert_mixed(from_file, to_file):
    f = open(from_file, "r")
    content = f.read()
    f.close()
    for x in re.findall(r"\\u([\da-f]{4})", content):
        content = content.replace(f"\\u{x}", chr(int(x, 16)))

    f = open(to_file, "w")
    f.write(content.replace("ö", "o"))


convert_mixed("file.txt", "out.txt")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文