python - 只保留字符串中的字母字符(多语言)

标签 python string multilingual

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

相关文章:

python - 从 Python : Python equivalent of . NET XmlTextWriter 写入 XML?

python - 在 Python 中为 GCP Dataflow 作业指定机器类型

java - 有没有办法强制异常消息为 Java 1.7 的英语

asp.net - 在 Windows Azure 中使用本地化资源时出现异常

python - 亚马逊 EC2 虚拟环境 : pip says it installed numpy but python can't find it

python - 收集桌面应用程序的使用数据

ios - 在 iOS Swift 中搜索多个子字符串的字符串

Java 1.7 仍然告诉我 switch 语句中的字符串不兼容

c# - C#中如何替换字符串中的字符

javascript - JavaScript中的多语言警报消息