s = 'ಆತಂಕವಾದಿಗಳಿಗೆ ವಿಶೇಷ ರಕ್ಷಣೆ ನೀಡುತ್ತದೆ, 24 ಕ್ಕೂ ಹೆಚ್ಚು ಹಿಂದೂ ಕಾರ್ಯಕರ್ತರ ಹತ್ಯೆಯಾದರೂ I am working on this'
words = re.findall(r'\w+',s)
print(words)
我原以为上面的代码只返回英文单词,但我得到的结果如下。
['ಆತ', 'ಕವ', 'ದ', 'ಗಳ', 'ಗ', 'ವ', 'ಶ', 'ಷ', 'ರಕ', 'ಷಣ', 'ನ', 'ಡ', 'ತ', 'ತದ',
'24', 'ಕ', 'ಕ', 'ಹ', 'ಚ', 'ಚ', 'ಹ', 'ದ', 'ಕ', 'ರ', 'ಯಕರ', 'ತರ', 'ಹತ', 'ಯ',
'ಯ', 'ದರ', 'I', 'am', 'working', 'on', 'this']
谁能解释一下这是如何工作的?
请您参考如下方法:
我不知道为什么你期望 \w+ 只匹配英文单词。它甚至不会在 ASCII 模式下执行此操作。它匹配任何 \w 字符序列,以及 docs描述 \w 的实际行为:
For Unicode (str) patterns:
Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is matched.For 8-bit (bytes) patterns:
Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_]. If the LOCALE flag is used, matches characters considered alphanumeric in the current locale and the underscore.
不幸的是,文档没有比这更具体,但是 \w 绝对不限于英语。
如果您想要[a-zA-Z0-9_],您可以明确写出您想要的字符类,或者您可以使用re.ASCII 标志。如果你想要 [a-zA-Z],请明确写出来。
