【问题标题】:Python descending order of wordcount [duplicate]Python的wordcount降序[重复]
【发布时间】:2014-04-20 08:38:58
【问题描述】:

我正在使用此代码来计算文本文件中单词出现的频率:

#!/usr/bin/python
file=open("out1.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

如何按频率数字的降序打印输出?

【问题讨论】:

  • 附带说明,不要忘记关闭文件。如果可能,我建议使用with 语句。

标签: python frequency word-count text-analysis


【解决方案1】:

使用Counter.most_common 而不指定值来获取单词频率的降序列表。

from collections import Counter

word_count = Counter()

with open("out1.txt","r+") as file:
    word_count.update((word for word in file.read().split()))

for word, count in word_count.most_common():
    print word, count

>>> the 6
Lorem 4
of 4
and 3
Ipsum 3
text 2
type 2

【讨论】:

    【解决方案2】:

    代码如下:

    file=open("out1.txt","r+")
    wordcount={}
    for word in file.read().split():
        word = word.lower()
        if word.isalpha == True:
            if word not in wordcount:
                wordcount[word] = 1
            else:
                wordcount[word] += 1
    copy = []
    for k,v in wordcount.items():
        copy.append((v, k))
    
    
    copy = sorted(copy, reverse=True)
    
    for k in copy:
            print '%s: %d' %(k[1], k[0])
    

    Out1.txt

    hello there I am saying hello world because Bob is here and I am saying hello because John is here
    

    运行方式

    hello: 3
    saying: 2
    is: 2
    here: 2
    because: 2
    am: 2
    I: 2
    world: 1
    there: 1
    and: 1
    John: 1
    Bob: 1
    

    【讨论】:

    • 完美运行!谢谢。
    • 没问题,很高兴为您提供帮助!
    • @loop_digga 请注意,如果您希望它不区分大小写或想要包含以句点结尾的单词等,这将不起作用。我确信 aj8uppal 知道如何将他的代码更改为让它发挥作用,但我认为你应该知道,这样你就不会因为为什么不将“这个这个”算作 2 个“这个”词而感到困惑。
    • @Human 谢谢,会检查的!
    • 我会编辑我的代码来解决这个问题,谢谢!
    【解决方案3】:

    您可以创建一个元组列表并对其进行排序。这是一个例子。

    wordcount = {'cat':1,'dog':2,'kangaroo':20}
    
    ls = [(k,v) for (k,v) in wordcount.items()]
    
    ls.sort(key=lambda x:x[1],reverse=True)
    
    for k,v in ls:
        print k, v
    

    ...输出...

    kangaroo 20
    dog 2
    cat 1
    

    【讨论】:

      【解决方案4】:

      使用Counter 模块。

      from collections import Counter
      
      s = "This is a sentence this is a this is this"
      
      c = Counter(s.split())
      #s.split() is an array of words, it splits it at each space if no parameter is given to split on
      
      print c
      
      >>> Counter({'is': 3, 'this': 3, 'a': 2, 'This': 1, 'sentence': 1})
      

      但对于句点和大写字母,这将无法“正确”工作。您可以简单地删除单词末尾的句点以正确计数,并将所有内容设置为小写/大写以使其不区分大小写。

      你可以摆脱这两个问题:

      s1 = "This is a sentence. This is a. This is. This."
      s2 = ""
      
      for word in s1.split():
          #punctuation checking, you can make this more robust through regex if you want
          if word.endswith('.') or word.endswith('!') or word.endswith('?'):
              s2 += word[:-1] + " "
          else:
              s2 += word + " "
      
      c = Counter(s2.lower().split())
      
      print c
      
      >>> Counter({'this': 4, 'is': 3, 'a': 2, 'sentence': 1})
      

      【讨论】:

        猜你喜欢
        • 2020-10-12
        • 2016-10-17
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 2016-03-03
        • 2015-12-08
        • 1970-01-01
        相关资源
        最近更新 更多