【问题标题】:Counting the number of unique words [duplicate]计算唯一词的数量[重复]
【发布时间】:2013-04-16 23:17:00
【问题描述】:

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

举个例子

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。问题是那个“男孩”。和 'boy' 的评价不同,因为标点符号。

【问题讨论】:

  • 请记住,实际数字是 14。因为你有三个词 boy,两个词 isnow

标签: python unique words


【解决方案1】:
import re
print len(re.findall('\w+', text))

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

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

【讨论】:

    【解决方案2】:

    你可以在这里使用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'])
    

    【讨论】:

      【解决方案3】:

      我认为您使用 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.

      【讨论】:

      • 如果字符串有 ,'?! 或任何其他字符怎么办?他是否也需要对这些检查进行硬编码?问题中的文字显然只是一个例子。
      • 他可以使用类似:punc_char= '.,!?'然后用它代替“硬代码”'。所以他会说 if letter in punc_char:
      【解决方案4】:

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

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

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

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

      现在,最后,您可以通过

      获得唯一词的数量
      len(cwords)
      

      【讨论】:

      • 请注意,您可以使用 collections.defaultdict(int)collections.Counter() 代替带有字典的 try/except。事实上,在这种情况下,看他只是想要唯一词的数量,你只需要一个set()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 2019-10-29
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多