我想获取文本中所有唯一字符的列表。该文本的一个特殊之处在于它包含 s̈、b̃ 等组合字符。所以当我分割文本时,特殊字符被分开。例如,这个字符 s̈ 被分成两个字符 s 和 ¡.
这是我要处理的文本示例。
sentence = "nejon ámas̈hó T̃iqu c̈ab̃op"
print(sentence)
print(list[set(sentence)])
我想获得一个包含独特字符的列表。对于这句话,这个列表应该是
expected_list = ['a', 'á', 'b̃', 'c̈', 'e', 'h', 'i', 'j', 'm', 'n', 'o', 'ó '、'p'、'q'、's̈'、'T̃'、'u']
但确实如此
实际列表 = ['j', 'p', 'c', 'n', 'a', ' ', 'i', 'á', 'o', 'T', 'u', '̃' , 'h', '̈', 'q', 's', 'e', 'm', 'b', 'ó']
我读到我可以按如下方式规范特殊字符
import unicodedata
# Only for the character s̈
print(ascii(unicodedata.normalize('NFC', '\u0073\u00a8'))) #prints 's\xa8'
但我不知道如何继续。任何帮助将不胜感激。
由于编码方式的性质,在 Python 中处理组合字符可能有点棘手。尝试
grapheme
库,它专门处理字素簇(显示为单个字符的文本单元)
使用 pip 安装
grapheme
库:
pip install grapheme
或者我更喜欢这种方式(以确保它安装到当前的 python 二进制目录)
python3 -m pip install grapheme
然后,您可以使用它从句子中提取独特的字素簇:
import grapheme
sentence = "nejon ámas̈hó T̃iqu c̈ab̃op"
unique_characters = list(grapheme.graphemes(sentence))
print(unique_characters)
替代 @bcstryker 的答案。 我的代码的唯一缺点是,它适用于大小为 1 和 2 的 unicode 字符。
import unicodedata
new_list = list()
pass_ = False # To ignore the unicode letters of size 2 from re-iterating
for i, x in enumerate(sentence):
if x == ' ': # Ignoring space
continue
if pass_:
pass_ = False
continue
if (i+1) != len(sentence):
n_sen = sentence[i+1]
if 'combining' in unicodedata.name(n_sen).lower(): # Checks if the characters is the unicode letter of size 2
if x+n_sen in new_list: # Checks if the letter already exists in the list
pass_ = True
continue
new_list += list([x+n_sen]) # Adds the unicode character combined
pass_ = True
continue
if x in new_list: # Checks if the letter already exists in the list
continue
new_list += x # Adds ascii letter and single size unicode special characters
print(new_list)
输出:
['n', 'e', 'j', 'o', 'á', 'm', 'a', 's̈', 'h', 'ó', 'T̃', 'i', 'q', 'u'、'c̈'、'b̃'、'p']