从给定字符串中删除包含数字的单词

2024-03-29 02:01:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个简单的程序,从接收到的字符串中删除所有包含数字的单词。在

以下是我当前的实现:

import re

def checkio(text):

    text = text.replace(",", " ").replace(".", " ") .replace("!", " ").replace("?", " ").lower()
    counter = 0
    words = text.split()

    print words

    for each in words:
        if bool(re.search(r'\d', each)):
            words.remove(each)

    print words

checkio("1a4 4ad, d89dfsfaj.")

但是,当我执行这个程序时,我得到以下输出:

^{pr2}$

我不明白为什么在第二行打印'4ad',因为它包含数字,应该从列表中删除。有什么想法吗?在


Tags: 字符串textimport程序redefcounter数字
3条回答

假设正则表达式执行所需的操作,可以这样做以避免在迭代时删除。在

import re

def checkio(text):

    text = re.sub('[,\.\?\!]', ' ', text).lower()
    words = [w for w in text.split() if not re.search(r'\d', w)]
    print words ## prints [] in this case

另外,请注意,我简化了您的text = text.replace(...)行。在

另外,如果不需要重用text变量,可以使用regex直接拆分它。在

^{pr2}$

这可以通过使用re.subre.search和{}来实现。在

>>> import re
>>> def checkio(s):
        print([i for i in re.sub(r'[.,!?]', '', s.lower()).split() if not re.search(r'\d', i)])


>>> checkio("1a4 4ad, d89dfsfaj.")
[]
>>> checkio("1a4 ?ad, d89dfsfaj.")
['ad']

如果要测试字母数字字符串,为什么不使用isalnum()而不是regex?在

In [1695]: x = ['1a4', '4ad', 'd89dfsfaj']

In [1696]: [word for word in x if not word.isalnum()]
Out[1696]: []

相关问题 更多 >