【发布时间】:2017-10-18 19:45:07
【问题描述】:
我有一个包含德语短语的文本文件,我正在尝试删除非字母字符,而不删除元音变音字符。我已经看到了其他类似的问题,但似乎没有一个解决方案对我有用。在某些情况下,Python 似乎将元音变音字符视为两个字符,但 print 函数工作正常:
>>> ch = '\xc3\xbc'
>>> print(ch)
ü
>>> print(len(ch))
2
>>> print(list(ch))
['\xc3', '\xbc']
我删除非字母字符的代码是
import unicodedata
def strip_po(s):
''.join(x for x in s if unicodedata.category(x) != 'Po')
word = strip_po(word)
Traceback (most recent call last):
File "/home/ed/Desktop/Deutsch/test", line 17, in <module>
word = strip_po(word)
File "/home/ed/Desktop/Deutsch/test", line 9, in strip_po
''.join(x for x in s if unicodedata.category(x) != 'Po')
File "/home/ed/Desktop/Deutsch/test", line 9, in <genexpr>
''.join(x for x in s if unicodedata.category(x) != 'Po')
TypeError: category() argument 1 must be unicode, not str
【问题讨论】:
-
你从哪里得到字符串?
-
你确定你在 Python 3 上运行它吗?
-
错误消息的“unicode, not str”位暗示您使用的是 Python 2,但您已将此问题标记为 Python 3。您实际使用的是哪一个? Unicode 处理在两个版本之间存在显着差异。
标签: python utf-8 python-3.6