计算唯一单词的数量

时间:2013-04-16 23:17:00

标签: python unique words

我想计算文本中的唯一单词,但我想确保特殊字符后面的单词不会被区别对待,并且评估不区分大小写。

举个例子

text = "There is one handsome boy. The boy has now grown up. He is no longer a boy now." 
print len(set(w.lower() for w in text.split()))

结果将是16,但我希望它会返回14.问题是'男孩'。由于标点符号,“男孩”的评价方式不同。

4 个答案:

答案 0 :(得分:2)

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

使用regular expression使这非常简单。您需要记住的是确保所有字符都在lowercase中,最后使用set合并结果,以确保没有重复的项目。

print len(set(re.findall('\w+', text.lower())))

答案 1 :(得分:1)

您可以在此处使用regex

In [65]: text = "There is one handsome boy. The boy has now grown up. He is no longer a boy now."

In [66]: import re

In [68]: set(m.group(0).lower() for m in re.finditer(r"\w+",text))

Out[68]: 
set(['grown',
     'boy',
     'he',
     'now',
     'longer',
     'no',
     'is',
     'there',
     'up',
     'one',
     'a',
     'the',
     'has',
     'handsome'])

答案 2 :(得分:1)

我认为你有正确的想法使用Python内置集类型。 我认为如果您先删除'。'就可以完成。通过替换:

text = "There is one handsome boy. The boy has now grown up. He is no longer a boy now."
punc_char= ",.?!'"
for letter in text:
    if letter == '"' or letter in punc_char:
        text= text.replace(letter, '')
text= set(text.split())
len(text)

应该适合你。如果您需要任何其他标志或标点符号,您可以轻松 将它们添加到punc_char中它们将被过滤掉。

亚伯拉罕J。

答案 3 :(得分:0)

首先,您需要获取单词列表。您可以使用正则表达式作为eandersson建议:

import re
words = re.findall('\w+', text)

现在,您想获得唯一条目的数量。有几种方法可以做到这一点。一种方法是遍历单词列表并使用字典来跟踪您看到单词的次数:

cwords = {}
for word in words:
     try:
         cwords[word] += 1
     except KeyError:
         cwords[word] = 1

现在,最后,您可以通过

获取唯一单词的数量
len(cwords)
相关问题