我正在从python中的网页中删除文本。
文本包含各种特殊的Unicode炭,例如心脏,笑容和其他野生东西。
通过使用content.encode('ascii', 'ignore')
,我能够将所有内容转换为ASCII,但这意味着所有重音的字符和突变的元音(例如'ä''或ß'也消失了。
如何保留"正常"炭,例如'ä'或'''完整但可以删除所有其他东西?
(我必须承认我是Python的新手,我从来没有真正落后于字符编码背后的所有魔力(。
从您的问题中不确定您在"好"one_answers"坏"字符之间划清界限,但您可能还不知道。Unicode包含许多不同类型的字符,您可能不知道多样性。
Unicode为每个字符分配一个类别,例如"字母,小写"或"标点符号,最终报价"或"符号,其他"。Python的STD LIB模块unicodedata
可让您方便地访问此信息:
>>> import unicodedata as ud
>>> ud.category('ä')
'Ll'
>>> ud.category('🙃')
'So'
从您的示例中,您认为您认为字母是好的,而符号是不好的。但是您也必须整理其余的。您可能还想保留空白("分离器"(和标点符号。而且您可能也需要标记,因为它们包括组合字符。
几个步骤:
您应该使用unicodedata.normalize('NFC', my_text)
标准化Unicode。并不是真正的问题,但是您必须有一个共同点,让我们拥有相同的字符以具有相同的编码。
然后,您应该检查每个角色以查看是否允许:
new_text = []
for c in my_normalized_text:
if ord(c) < 128:
# this is optional, it add ascii character as they are
# possibly you want to tokenize (see later, how we replace punctuation)
new_text.append(c)
continue
cat = unicodedata.category(c)
if cat in {'Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nd'}:
new_text.append(c)
elif cat in {'Mc', 'Pc', 'Pd', 'Ps', 'Pe', 'Pi', 'Of', 'Po', 'Zs', 'Zl', 'Zp'}:
# this tokenize
new_text.append(' ')
# else: do not append. You may still append ' ' and remove above check.
您应该根据您的下一个处理方法进行调整:请参阅Python Unicode Howto和链接页面Unicode字符类别。
好吧,我终于使用了:
# create translation map for non-bmp charactes
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
# strip unwanted unicode images
question = question.translate(non_bmp_map)
# convert to latin-1 to remove all stupid unicode characters
# you may want to adapt this to your personal needs
#
# for some strange reason I have to first transform the string to bytes with latin-1
# encoding and then do the reverse transform from bytes to string with latin-1 encoding as
# well... maybe has to be revised later
bQuestion = question.encode('latin-1', 'ignore')
question = bQuestion.decode('latin-1', 'ignore')
感谢任何回答的人