【问题标题】:Set of hidden unicode characters in a string字符串中隐藏的 unicode 字符集
【发布时间】:2019-01-30 09:17:32
【问题描述】:

一些隐藏的 Unicode 字符集出现在需要删除的字符串中。

我有一个非常大的文本,它是使用 PyPDF2 包从 PDF 文件中提取的。现在这个提取的文本有很多问题(比如PDF中的表格中的文本在提取时会随机出现),并且很多特殊字符也嵌入其中(如~~~~~~~,}}} }}}}} 等)虽然这些文本在作为 PDF 文件查看时不存在。我尝试使用thisthisthis 链接中描述的解决方案删除这些字符,但问题仍然出现

myText = "There is a set of hidden character here => <= but it will get printed in console"

print(myText)

现在我想要一个没有那些隐藏字符的干净文本。

【问题讨论】:

  • 为了获得 => 和 =
  • 这样做的结果是什么:print(repr(s.encode('ascii', 'ignore')))? (来自其中一个链接)
  • 这是结果b'There is a set of hidden character here =&gt;\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f &lt;= but i will get printed in console'
  • 这是唯一一个你有问题的隐藏角色吗?
  • 现在,是的。如果这个问题得到解决,也许我可以找到其他特殊字符的方法。

标签: python python-3.x unicode python-unicode


【解决方案1】:

字符\x7fascii character DEL,这解释了为什么您的尝试没有成功。要删除所有“特殊” ascii 字符,请使用以下代码:

请参阅此处查看 bytes.decode documentation

import string
a = b'There is a set of hidden character here =>\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f <= but i will get printed in console'
print(repr(a))
print(repr(''.join(i for i in a.decode('ascii', 'ignore') if i in string.printable)))

如果不是,你不想导入字符串:

a = b'There is a set of hidden character here =>\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f <= but i will get printed in console'
print(repr(a))
print(repr(''.join(i for i in a.decode('ascii', 'ignore') if 31 < ord(i) < 127 or i in '\r\n')))

【讨论】:

  • 它仍然对我不起作用,因为在我的情况下,字符串前面有一个字符'b'。我建议将您的字符串修改为a = b'There is a set of hidden character here =&gt;\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f &lt;= but i will get printed in console'
  • @mdowes 然后你有一个字节串,而不是一个字符串。我更新了代码来处理这个问题。
猜你喜欢
  • 1970-01-01
  • 2013-02-21
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
相关资源
最近更新 更多