繁体   English   中英

尝试在文本文件中输出x个最常用的单词

[英]Trying to output the x most common words in a text file

我正在尝试编写一个程序,该程序将在文本文件中读取并输出最常用单词(现在写入代码时为30)及其计数的列表。 所以像这样:

word1 count1
word2 count2
word3 count3
...   ...
...   ...
wordn countn

顺序为count1> count2> count3> ...> countn。 到目前为止,这是我所拥有的,但是我无法获得排序后的函数来执行所需的功能。 我现在得到的错误是:

TypeError: list indices must be integers, not tuple

我是python的新手。 任何帮助,将不胜感激。 谢谢。

 def count_func(dictionary_list):
  return dictionary_list[1]

def print_top(filename):
  word_list = {}
  with open(filename, 'r') as input_file:

    count = 0

    #best
    for line in input_file:
      for word in line.split():
        word = word.lower()
        if word not in word_list:
          word_list[word] = 1
        else:
          word_list[word] += 1

#sorted_x = sorted(word_list.items(), key=operator.itemgetter(1))
#  items = sorted(word_count.items(), key=get_count, reverse=True)

  word_list = sorted(word_list.items(), key=lambda x: x[1])

  for word in word_list:
    if (count > 30):#19
      break
    print "%s: %s" % (word, word_list[word])
    count += 1


# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'
    sys.exit(1)

  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
    print_words(filename)
  elif option == '--topcount':
    print_top(filename)
  else:
    print 'unknown option: ' + option
    sys.exit(1)

if __name__ == '__main__':
  main()

使用collections.Counter类。

from collections import Counter

for word, count in Counter(words).most_common(30):
    print(word, count)

一些不请自来的建议:在一切都作为一个大代码块工作之前,不要做太多的功能。 在工作重构为函数。 这么小的脚本,您甚至不需要一个主要部分。

使用itertoolsgroupby

from itertools import groupby

words = sorted([w.lower() for w in open("/path/to/file").read().split()])
count = [[item[0], len(list(item[1]))] for item in groupby(words)]
count.sort(key=lambda x: x[1], reverse = True)
for item in count[:5]:
    print(*item)
  • 这将列出文件中的单词,对其进行排序,并列出唯一单词及其出现。 随后,发现名单是发生排序方式:

     count.sort(key=lambda x: x[1], reverse = True) 
  • reverse = True是首先列出最常见的单词。

  • 在该行中:

     for item in count[:5]: 

    [:5]定义要显示的最多出现的单词数。

其他人建议的第一种方法,即通过使用most_common(...)不能根据您的需要运行,因为它返回第n个最常见的单词,而不是返回计数小于或等于n的单词:

这里使用most_common(...) :请注意,它仅显示前n个最常用的单词:

>>> import re
... from collections import Counter
... def print_top(filename, max_count):
...     words = re.findall(r'\w+', open(filename).read().lower())
...     for word, count in Counter(words).most_common(max_count):
...         print word, count
... print_top('n.sh', 1)
force 1

正确的方法如下,请注意,它将打印计数小于等于count的所有单词:

>>> import re
... from collections import Counter
... def print_top(filename, max_count):
...     words = re.findall(r'\w+', open(filename).read().lower())
...     for word, count in filter(lambda x: x[1]<=max_count, sorted(Counter(words).items(), key=lambda x: x[1], reverse=True)):
...         print word, count
... print_top('n.sh', 1)
force 1
in 1
done 1
mysql 1
yes 1
egrep 1
for 1
1 1
print 1
bin 1
do 1
awk 1
reinstall 1
bash 1
mythtv 1
selections 1
install 1
v 1
y 1

这是我的python3解决方案。 在面试中有人问我这个问题,访调员很高兴这个解决方案,尽管在较少时间限制的情况下,上面提供的其他解决方案对我来说似乎更好。

    dict_count = {}
    lines = []

    file = open("logdata.txt", "r")

    for line in file:# open("logdata.txt", "r"):
        lines.append(line.replace('\n', ''))

    for line in lines:
        if line not in dict_count:
            dict_count[line] = 1
        else:
            num = dict_count[line]
            dict_count[line] = (num + 1)

    def greatest(words):
        greatest = 0
        string = ''
        for key, val in words.items():
            if val > greatest:
                greatest = val
                string = key
        return [greatest, string]

    most_common = []
    def n_most_common_words(n, words):
        while len(most_common) < n:
            most_common.append(greatest(words))
            del words[(greatest(words)[1])]

    n_most_common_words(20, dict_count)

    print(most_common)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM