gpt4 book ai didi

python - 正则表达式仅搜索单词

转载 作者:行者123 更新时间:2023-12-01 04:27:34 24 4
gpt4 key购买 nike

我有这个正则表达式,在 http://regexpal.com/ 中运行良好:

[^-:1234567890/.,\s]*

我试图在一个充满( , . # ""\n\s...etc)的段落中找到这些单词

但在我的代码中我看不到我正在观察的结果:

def words(lines):
words_pattern = re.compile(r'[^-:1234567890/.,\s]*')
li = []
for m in lines:
e = words_pattern.search(m)
if e:
match = e.group()
li.append(match)
return li

li = [u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'']

对此有什么建议吗?也许我没有以正确的方式从一个地方到另一个地方遍历正则表达式

提前致谢

编辑

更准确地说,我确实想要:ñ á é í ó 和 ú

谢谢

最佳答案

如果您只想要字母,可以使用string.ascii_letters

>>> from string import ascii_letters
>>> import re
>>> s = 'this is 123 some text! that has someñ \n other stuff.'
>>> re.findall('[{}]+'.format(ascii_letters), s)
['this', 'is', 'some', 'text', 'that', 'has', 'some', 'other', 'stuff']

您还可以从 [A-Za-z] 获得相同的行为(本质上与 string.ascii_letters 相同)

>>> re.findall('[A-Za-z]+', s)
['this', 'is', 'some', 'text', 'that', 'has', 'some', 'other', 'stuff']

关于python - 正则表达式仅搜索单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32870159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com