在 stackoverflow 上有很多关于如何只保留字符串中的字母字符的答案,最常见的答案是著名的正则表达式 '[^a-zA-Z]'
。但是这个答案是完全错误的,因为它假设每个人都只写英文......我以为我可以否决所有这些答案,但我最终认为再次提出这个问题会更有建设性,因为我找不到答案。
在 python 中是否有一种简单(或不......)的方法来只保留适用于所有语言的字符串中的字母字符?我想也许有一个图书馆可以像 xregexp 那样做在 javascript 中...所有语言我指的是英语,还有法语、俄语、中文、希腊语...等
最佳答案
[^\W\d_]
使用 Python3 或 Python2 中的 re.UNICODE
标志,您可以使用 [^\W\d_]
。
\W : If UNICODE is set, this will match anything other than [0-9_] plus characters classified as not alphanumeric in the Unicode character properties database.
所以 [^\W\d_]
是任何不是字母数字或数字或下划线的东西。换句话说,它是任何字母字符。 :)
>>> import re
>>> re.findall("[^\W\d_]", "jüste Ä tösté 1234 ßÜ א д", re.UNICODE)
['j', 'ü', 's', 't', 'e', 'Ä', 't', 'ö', 's', 't', 'é', 'ß', 'Ü', 'א', 'д']
先去掉数字,再找“\w”
为了避免这种复杂的逻辑,您也可以先删除数字和下划线,然后再查找字母数字字符:
>>> without_digit = re.sub("[\d_]", "", "jüste Ä tösté 1234 ßÜ א д", re.UNICODE)
>>> re.findall("\w", without_digit, re.UNICODE)
['j', 'ü', 's', 't', 'e', 'Ä', 't', 'ö', 's', 't', 'é', 'ß', 'Ü', 'א', 'д']
正则表达式模块
似乎regex
模块可以提供帮助,因为它理解 \p{L}
或 [\w--\d_]
。
This regex implementation is backwards-compatible with the standard ‘re’ module, but offers additional functionality.
>>> import regex as re
>>> re.findall("\p{L}", "jüste Ä tösté 1234 ßÜ א д", re.UNICODE)
['j', 'ü', 's', 't', 'e', 'Ä', 't', 'ö', 's', 't', 'é', 'ß', 'Ü', 'א', 'д']
(使用 Anaconda Python 3.6 测试)
关于python - 只保留字符串中的字母字符(多语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44779330/