繁体   English   中英

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

[英]How to use the regex module in python to split a string of text into the words only?

这就是我正在合作的东西...

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? 我似乎无法摆脱'' (空字符串)! 它让我发疯。

因为尽管它根据最后一个点进行拆分,但它也会给出最后一个空白部分。

您根据\\W+分割了输入字符串,这意味着根据一个或多个非单词字符分割了输入字符串。 因此,您的正则表达式也匹配最后一个点,并根据最后一个点分割输入。 由于最后一个点之后没有字符串,因此分割后返回空字符串。

Avinash Raj正确地指出了为什么这样做。 解决方法如下:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM