如何在python中的500个文本文件中查找500个最常用的单词?

如何在python中的500个文本文件中查找500个最常用的单词?,python,python-2.7,text-processing,Python,Python 2.7,Text Processing,我在一个目录中有500个文本文件。我必须在所有文本文件的组合中找到500个最常用的单词。我如何才能做到这一点 PS:我搜索了很多,但找不到解决方案。这是我能想到的使用字典进行计数的最简单的方法,用关键字作为单词,用值作为计数: import os # word counts are stored in a dictionary # for fast access and duplication prevention count = {} # your text files should be i

我在一个目录中有500个文本文件。我必须在所有文本文件的组合中找到500个最常用的单词。我如何才能做到这一点


PS:我搜索了很多,但找不到解决方案。

这是我能想到的使用字典进行计数的最简单的方法,用关键字作为单词,用值作为计数:

import os
# word counts are stored in a dictionary
# for fast access and duplication prevention
count = {}
# your text files should be in this folder
DIR = "files"
# iterate over all files in the folder
for filename in os.listdir(DIR):
    with open(os.path.sep.join([DIR, filename]), 'r') as f:
        for line in f.readlines():
            # strip line separators from end of line
            line = line.strip()
            # once we have a line from the file, split it to words, and
            # add word to the scores (if it's new), or increase it's count
            for word in line.split():
                if word in count:
                    # existing
                    count[word] = count[word] + 1
                else:
                    # new
                    count[word] = 1
print sorted(count.items(), key=lambda x: x[1], reverse=True)[:500]
使用(如Padraic建议):


您可以为每个新词创建一个计数器和一个单词数组。将每个新词添加到数组中。使用“索引”将文本文件中的每个字与数组中的字进行比较,增加该字的计数器。或者您可以创建一个数组,用每个新数组填充 从文本文件中,使用数组的第二个元素作为计数器

使用:


当然,它将读取该目录中找到的每个文件。如果这不是预期的行为,请使用所需的模式,而不是
os.listdir
(请参阅Reut对我的答案的评论)。

我们可以使用collections模块中的计数器方法

  • 通过
    glob
  • 通过
    for loop
    迭代步骤1中的所有文件
  • 使用
    语句和
    read()
    文件对象方法以读取模式打开文件
  • 通过字符串的
    Split()
    方法拆分文件内容,并使用
    计数器创建可计数字典。将两个计数器相加
    
  • 通过
    most\u common(3)
    方法从计数器中获取最常用的单词
  • 代码:

    输出:-

    vivek@vivek:~/Desktop$ python 4.py 
    main_counter:- Counter({'This': 3, 'try': 2, 'again.': 2, 'is': 2, 'can': 2, 'file': 2, 'you': 2, 'my': 2, '1': 1, 'this': 1, '2': 1})
    most common 3:- [('This', 3), ('try', 2), ('again.', 2)]
    

    你考虑过数数吗?但说真的,你被困在哪里了?你到哪里去了?是的,我现在就试试。但你也可以试试。(vivke.igp是我的skype id)我可以处理单个文件,但如何合并所有文本文件的结果?只需创建每个文件的所有字典的一个计数器字典。检查我的解决方案,它与abcj类似,只需使用计数器dict,也只需迭代file对象,无需创建列表,除非您确实需要it@PadraicCunningham,谢谢,我第一次使用它。你可以把一个数字传给最普通的人,你不需要知道这个数字是否处理换行?@ReutSharabani no,split()他们玩得很好。只有一件事,也许您应该
    glob
    按扩展名将文件/指定文件夹设置为
    os.listdir
    。。。否则代码本身也将被计算:)
    import os
    from collections import Counter
    
    c, directory = Counter(), 'path_to_your_directory'
    
    for x in os.listdir(directory):
        fname = os.path.join(directory, x)
        if os.path.isfile(fname):
            with open(fname) as f:
                c += Counter(f.read().split())
    
    for word, _ in c.most_common(500):
        print(word)
    
    from glob import glob 
    from  collections import Counter
    
    p = "/home/vivek/Desktop/test/*.txt"
    main_counter = Counter()
    
    for i in glob(p):
        with open(i, "rb") as fp:
            main_counter += Counter(fp.read().split())
    
    print "main_counter:-", main_counter
    print "most common 3:-", main_counter.most_common(3)
    
    vivek@vivek:~/Desktop$ python 4.py 
    main_counter:- Counter({'This': 3, 'try': 2, 'again.': 2, 'is': 2, 'can': 2, 'file': 2, 'you': 2, 'my': 2, '1': 1, 'this': 1, '2': 1})
    most common 3:- [('This', 3), ('try', 2), ('again.', 2)]