如何在 Python 中使用德语变音字符

How to work with German umlaut characters in Python

我有一个包含德语短语的文本文件,我正在尝试删除非字母字符,而不删除元音变音字符。我已经看到其他类似的问题,但 none 的解决方案似乎对我有用。 Python 似乎在某些情况下将变音字符视为两个字符,但打印功能工作正常:

>>> 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

我假设您在这种情况下使用 Python2,因为我可以用 Py2 重现您的问题。

您不想使用字节进行任何文本处理。 Python 2 str 类型实际上只是一个字节列表,这就是为什么 len 说你的字符是 2 个字节长。你想把这些字节变成 unicode 类型。你可以这样做:

In [1]: '\xc3\xbc'.decode('utf8')
Out[1]: u'\xfc'

注意 运行 len 将产生 1,因为它现在只是一个 unicode 字符。现在你可以正常处理你的文本,那个字符: unicodedata.category(u'\xfc') 属于类别 'Ll'

您可能想要隐藏的类别不只是 Po。这里有一个完整的列表: https://en.wikipedia.org/wiki/Unicode_character_property

Python 内置的 isalpha 方法在这里可能对您有帮助,但是您希望类型首先是 unicode,如上所示。 https://docs.python.org/2/library/stdtypes.html#str.isalpha

In [2]: u'\xfc'.isalpha()
Out[2]: True