如何在python中使用正则表达式模块将文本字符串分割成单词? [英] How to use the regex module in python to split a string of text into the words only?

查看:313
本文介绍了如何在python中使用正则表达式模块将文本字符串分割成单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用...

  string1 =狗,猫,老鼠,鸟,人类。 

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

返回文本

打印string_count(string1)

...这里是输出...

  1 

2

3
鼠标
4

5
人类
6

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

为什么我得到6,即使只有5个字?我似乎无法摆脱''(空字符串)!

解决方案

因为当它基于最后一个点分裂时,它也会给出最后一个空白部分。 p>

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


Here's what I'm working with…

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)

…and here's the output…

1
Dog
2
cat
3
mouse
4
bird
5
Human
6

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

Why am I getting a 6 even though there are only 5 words? I can't seem to get rid of the '' (empty string)! It's driving me insane.

解决方案

Because while it splits based on the last dot, it gives the last empty part also.

You splitted the input string based on \W+ which means split the input string based on one or more non-word character. So your regex matches the last dot also and splits the input based on the last dot also. Because of no string present after to the last dot, it returns an empty string after splitting.

这篇关于如何在python中使用正则表达式模块将文本字符串分割成单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆