【问题标题】:Remove Unicode code (\uxxx) in string Python删除字符串 Python 中的 Unicode 代码 (\uxxx)
【发布时间】:2017-10-16 01:58:36
【问题描述】:

我的文档中有一些 Unicode 字符串。我想要的只是删除这个 Unicode 代码或用一些空格(“”)替换它。示例=""

doc = "Hello my name is Ruth \u2026! I really like swimming and dancing \ud83c"

如何将其转换为以下内容?

doc = "Hello my name is Ruth! I really like swimming and dancing"

我已经尝试过:https://stackoverflow.com/a/20078869/5505608,但没有任何反应。我正在使用 Python 3。

【问题讨论】:

  • 如果您链接的答案不起作用,则说明您没有告诉我们。
  • 我已经尝试过re.sub(r'[^\x00-\x7F]+',' ', text)。代码有效,但没有任何改变@MarkRansom
  • 这是因为字符串不会就地更新,它们是不可变的。你需要把re.sub的返回值赋值给text

标签: python regex python-3.x unicode


【解决方案1】:

您可以编码为 ASCII 并忽略错误(即无法转换为 ASCII 字符的代码点)。

>>> doc = "Hello my name is Ruth \u2026! I really like swimming and dancing \ud83c"
>>> doc.encode('ascii', errors='ignore')
b'Hello my name is Ruth ! I really like swimming and dancing '

如果尾随空格困扰您,strip 将其关闭。根据您的用例,您可以使用 ASCII 再次解码结果。链接所有内容如下所示:

>>> doc.encode('ascii', errors='ignore').strip().decode('ascii')
'Hello my name is Ruth ! I really like swimming and dancing'

【讨论】:

  • 我已经尝试过编码,代码可以工作,但仍然没有任何变化。感谢您的回复。
  • 我的目的是从我流式传输的推文中清除 unicode 代码。我尝试了包含 10 条推文的 tweet.txt 代码。
  • 哪一个? @timgeb
  • 答案中的那个。
  • 使用tweet.encode('ascii', errors='ignore')后仍出现unicode码
猜你喜欢
  • 2012-04-25
  • 2016-08-29
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 2019-11-26
相关资源
最近更新 更多