【问题标题】:Can I replace a string with 5 digit unicode in Python?un [closed]我可以在 Python 中用 5 位 unicode 替换字符串吗? [关闭]
【发布时间】:2013-02-05 13:29:16
【问题描述】:

早些时候,我问过这个问题: How to convert some character into five digit unicode one in Python 3.3?

但是今天我发现大写 U 代码点在打印时有效,但是当我在文件中尝试时,结果却失败了。为什么?

import re

f = codecs.open('test.txt', 'r', encoding="utf-8")
g = codecs.open('test_output.txt', 'w', encoding="utf-8")
fin = f.read()
output = re.sub('m', '\U000243D0', fin)
g.write(output)

【问题讨论】:

  • 失败如何准确?您的代码在这里没有任何问题,您得到的输出与您预期的输出是什么?
  • @dan04:codecs 用法指向 Python 2;在 Python 3 中,您只需使用 open()通常
  • 我使用的是 Python 3.3。奇怪的是,m 被 ए 取代了。它的代码点是 \u090F。
  • @user1610952:你用什么来测试数据? \u090F 编码为 UTF-8 为\xE0\xA4\x8F(三个字节以\xE0 开头),\U000243D0 编码为\xF0\xA4\x8F\x90;如果您从第一个字节中删除 1 位并忽略 \x90 字节,则会出现重叠。 Python 不这样做(我测试过),那么您使用什么工具会损坏数据或曲解数据?

标签: python unicode


【解决方案1】:

这对我来说很好用:

import re

with open('/tmp/test.txt', 'w', encoding='utf8') as testfile:
    testfile.write("I don't go to school on mondays")

with open('/tmp/test.txt', 'r', encoding='utf8') as testfile, open('/tmp/test_output.txt', 'w', encoding='utf8') as testout:
    output = re.sub('m', '\U000243D0', testfile.read())
    testout.write(output)

with open('/tmp/test_output.txt', 'r', encoding='utf8') as testfile:
    print(repr(testfile.read()))

输出

"I don't go to school on ?ondays"

【讨论】:

  • 请注意,在 2.6 和 2.7 中,您可以使用语句 from __future__ import unicode_literals 使字符串默认具有 unicode 类型。
  • @dan04:当然,这对于编写需要在 python 2 python 3 上运行的代码的人来说非常棒,但对于大多数只针对 one的开发人员来说> 版本,通常没有那么有用。 :-)
  • 谢谢,但我使用的是 Python 3.3。我仍然不明白为什么它不起作用。
  • @user1610952:那么请显示(摘录)写入文件的输出,以及您期望的输出。您可以使用 python 读取它并向我们展示您想要更正的字节的repr()
  • test.txt 是:我星期一不上学。它变成了这个(test_out.txt):我在एondays不去学校。我的预期是:我每天?不上学。
猜你喜欢
  • 2011-02-20
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
相关资源
最近更新 更多