python:senten中的count word标记

2024-06-17 15:16:35 发布

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

我在数一数字符串中的单词数。不过,我首先得去掉一些标点符号,例如

line = "i want you , to know , my name . "

跑步

en = line.translate(string.maketrans('', ''), '!,.?')

产生

en = "i want you  to know  my name  "

在这之后,我想数一数行中的单词数。但当我完成时,我得到的是30而不是7。

在所有情况下,在en上使用split来标记和查找长度并不都有效。e、 g

我试过它不总是有效的。e、 考虑一下这根绳子。

"i ccc bcc the a of the abc ccc dd on aaa , 28 abc 19 ."

然后,en变成:

"i ccc bcc the a of the abc ccc dd on aaa 28 abc 19 "

但是len(en)返回17而不是15。

你能帮忙吗?谢谢


Tags: ofthetonameyoumyline单词
3条回答

您可以使用NLTK

import nltk
en = "i ccc bcc the a of the abc ccc dd on aaa 28 abc 19 "
print(len(nltk.word_tokenize(en)))

输出:

15

en.split(' ')的问题是字符串中有额外的空格,它给出空匹配。您可以通过调用en.split()来很容易地解决这个问题。

但也许您可以使用正则表达式使用这种不同的方法(现在不需要先删除标点符号):

import re
print len(re.findall(r'\w+', line))

在线查看工作:ideone

使用\b来计算单词比使用regex\w+要快得多,例如:

import re
_re_word_boundaries = re.compile(r'\b')

def num_words(line):
    return len(_re_word_boundaries.findall(line)) >> 1

注意,我们必须将数字减半,因为\b在单词的开头和结尾都匹配。不幸的是,与egrep不同,Python不支持只在开头或结尾进行匹配。

如果您有很长的行并且关心内存,那么使用迭代器可能是更好的解决方案:

def num_words(line):
    return sum(1 for word in _re_word_boundaries.finditer(line)) >> 1

相关问题 更多 >