正则表达式跳过某些特定字符

Raj*_*ooq 4 python regex string python-2.7

我试图清理字符串,使其没有任何标点或数字,它必须只有az和AZ.例如,给定String是:

"coMPuter scien_tist-s are,,,  the  rock__stars of tomorrow_ <cool>  ????"
Run Code Online (Sandbox Code Playgroud)

所需的输出是:

['computer', 'scientists', 'are', 'the', 'rockstars', 'of', 'tomorrow']
Run Code Online (Sandbox Code Playgroud)

我的解决方案是

re.findall(r"([A-Za-z]+)" ,string)
Run Code Online (Sandbox Code Playgroud)

我的输出是

['coMPuter', 'scien', 'tist', 's', 'are', 'the', 'rock', 'stars', 'of', 'tomorrow', 'cool']
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 5

您不需要使用正则表达式:

(如果你想要所有小写单词,请将字符串转换为小写),拆分单词,然后过滤掉以字母开头的单词:

>>> s = "coMPuter scien_tist-s are,,,  the  rock__stars of tomorrow_ <cool>  ????"
>>> [filter(str.isalpha, word) for word in s.lower().split() if word[0].isalpha()]
['computer', 'scientists', 'are', 'the', 'rockstars', 'of', 'tomorrow']
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中,filter(str.isalpha, word)应该替换为''.join(filter(str.isalpha, word)),因为在Python 3.x中,filter返回一个过滤器对象.