gpt4 book ai didi

Python - 查找文本文件中单词列表的单词频率

转载 作者:太空狗 更新时间:2023-10-29 17:27:04 27 4
gpt4 key购买 nike

我正在努力加快我的项目以计算词频。我有 360 多个文本文件,我需要获取单词总数和另一个单词列表中每个单词出现的次数。我知道如何使用单个文本文件执行此操作。

>>> import nltk
>>> import os
>>> os.chdir("C:\Users\Cameron\Desktop\PDF-to-txt")
>>> filename="1976.03.txt"
>>> textfile=open(filename,"r")
>>> inputString=textfile.read()
>>> word_list=re.split('\s+',file(filename).read().lower())
>>> print 'Words in text:', len(word_list)
#spits out number of words in the textfile
>>> word_list.count('inflation')
#spits out number of times 'inflation' occurs in the textfile
>>>word_list.count('jobs')
>>>word_list.count('output')

获取“通货膨胀”、“工作”、“产出”的频率太繁琐了。我可以把这些词放到一个列表中,同时求出列表中所有词的出现频率吗?基本上 this用 Python。

例子:代替这个:

>>> word_list.count('inflation')
3
>>> word_list.count('jobs')
5
>>> word_list.count('output')
1

我想这样做(我知道这不是真正的代码,这就是我寻求帮助的原因):

>>> list1='inflation', 'jobs', 'output'
>>>word_list.count(list1)
'inflation', 'jobs', 'output'
3, 5, 1

我的单词列表将包含 10-20 个术语,因此我需要能够将 Python 指向单词列表以获得计数。如果输出能够复制+粘贴到 excel 电子表格中,将单词作为列,频率作为行,那也很好

例子:

inflation, jobs, output
3, 5, 1

最后,任何人都可以帮助为所有文本文件自动执行此操作吗?我想我只是将 Python 指向该文件夹,它可以从新列表中为 360 多个文本文件中的每一个进行上述字数统计。看起来很容易,但我有点卡住了。有什么帮助吗?

像这样的输出会很棒: 文件名1 通货膨胀、就业、产出 3, 5, 1

Filename2
inflation, jobs, output
7, 2, 4

Filename3
inflation, jobs, output
9, 3, 5

谢谢!

最佳答案

collections.Counter()如果我了解您的问题,是否涵盖了这一点。

文档中的示例似乎符合您的问题。

# Tally occurrences of words in a list
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
print cnt


# Find the ten most common words in Hamlet
import re
words = re.findall('\w+', open('hamlet.txt').read().lower())
Counter(words).most_common(10)

从上面的例子你应该能够做到:

import re
import collections
words = re.findall('\w+', open('1976.03.txt').read().lower())
print collections.Counter(words)

编辑 以一种方式显示的天真方法。

wanted = "fish chips steak"
cnt = Counter()
words = re.findall('\w+', open('1976.03.txt').read().lower())
for word in words:
if word in wanted:
cnt[word] += 1
print cnt

关于Python - 查找文本文件中单词列表的单词频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14921436/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com