gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:02:18 24 4
gpt4 key购买 nike

我正在尝试清理字符串,使其没有任何标点符号或数字,它必须只有 a-z 和 A-Z。例如,给定的字符串是:

"coMPuter scien_tist-s are,,,  the  rock__stars of tomorrow_ <cool>  ????"

要求的输出是:

['computer', 'scientists', 'are', 'the', 'rockstars', 'of', 'tomorrow']

我的解决方案是

re.findall(r"([A-Za-z]+)" ,string)

我的输出是

['coMPuter', 'scien', 'tist', 's', 'are', 'the', 'rock', 'stars', 'of', 'tomorrow', 'cool']

最佳答案

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

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

>>> 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']

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

关于python - 跳过某些特定字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42591809/

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