如何使用python中的regex模块将文本字符串拆分为单词?

2024-04-26 20:29:30 发布

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

这就是我的工作

string1 = "Dog,cat,mouse,bird. Human."

def string_count(text):
    text = re.split('\W+', text)
    count = 0
    for x in text:
        count += 1
        print count
        print x

return text

print string_count(string1)

…这是输出

1
Dog
2
cat
3
mouse
4
bird
5
Human
6

['Dog', 'cat', 'mouse', 'bird', 'Human', '']

为什么我只有5个字却得了6分?我似乎无法摆脱''(空字符串)!快把我逼疯了。你知道吗


Tags: textinreforstringdefcountcat
2条回答

因为当它基于最后一个点进行分割时,它也给出了最后一个空的部分。你知道吗

您基于\W+分割了输入字符串,这意味着基于一个或多个非单词字符分割了输入字符串。所以正则表达式也匹配最后一个点,并基于最后一个点分割输入。由于到最后一个点后不存在字符串,因此拆分后返回空字符串。你知道吗

阿维纳什·拉吉正确地说明了它为什么这么做。以下是修复方法:

string1 = "Dog,cat,mouse,bird. Human."
the_list = [word for word in re.split('\W+', string1) if word]
# include the word in the list if it's not the empty string

或者(这更好……)

string1 = "Dog,cat,mouse,bird. Human."
the_list = re.findall('\w+', string1)
# find all words in string1

相关问题 更多 >