统计(并记录)文本文件中每行单词频率的方法

3

这是我第一次在 Stack 上发布问题,通常以前的问题都足够解决我的问题!我主要遇到的问题是逻辑问题......即使提供伪代码答案也很好。

我正在使用 Python 从文本文件的每一行读取数据,格式如下:

This is a tweet captured from the twitter api #hashtag http://url.com/site

使用nltk,我可以按行进行分词,然后可以使用reader.sents()进行迭代等操作。
reader = TaggedCorpusReader(filecorpus, r'.*\.txt', sent_tokenizer=Line_Tokenizer())

reader.sents()[:10]

我想要统计每行中特定“热词”的频率(存储在数组或类似结构中),然后将它们写回到文本文件中。如果使用reader.words(),可以统计整个文本中“热词”的频率,但我要求每行(或在这种情况下是“句子”)的数量。

理想情况下,代码应该像这样:

hotwords = (['tweet'], ['twitter'])

for each line
     tokenize into words.
     for each word in line 
         if word is equal to hotword[1], hotword1 count ++
         if word is equal to hotword[2], hotword2 count ++
     at end of line, for each hotword[index]
         filewrite count,

此外,不太担心 URL 变得无法使用(使用 WordPunctTokenizer 将删除标点符号 - 这不是问题)。

任何有用的提示(包括伪代码或链接到其他类似代码的链接)都将非常棒。

---- 编辑 ------------------

最终做了这样的事情:

import nltk
from nltk.corpus.reader import TaggedCorpusReader
from nltk.tokenize import LineTokenizer
#from nltk.tokenize import WordPunctTokenizer
from collections import defaultdict

# Create reader and generate corpus from all txt files in dir.
filecorpus = 'Twitter/FINAL_RESULTS/tweetcorpus'
filereader = TaggedCorpusReader(filecorpus, r'.*\.csv', sent_tokenizer=LineTokenizer())
print "Reader accessible." 
print filereader.fileids()

#define hotwords
hotwords = ('cool','foo','bar')

tweetdict = []

for line in filereader.sents():
wordcounts = defaultdict(int)
    for word in line:
        if word in hotwords:
            wordcounts[word] += 1
    tweetdict.append(wordcounts)

输出结果如下:

print tweetdict

[defaultdict(<type 'dict'>, {}),
 defaultdict(<type 'int'>, {'foo': 2, 'bar': 1, 'cool': 2}),
 defaultdict(<type 'int'>, {'cool': 1})]
3个回答

4
from collections import Counter

hotwords = ('tweet', 'twitter')

lines = "a b c tweet d e f\ng h i j k   twitter\n\na"

c = Counter(lines.split())

for hotword in hotwords:
    print hotword, c[hotword]

该脚本适用于Python 2.7及以上版本。


你也可以像这样使用 most_common,比如 c.most_common(10),来获取计数器中出现频率最高的前10个单词。 - razpeitia
我本来打算建议使用一个字典 {String word:int count},就像 @Daniel Roseman 说的那样,但这个看起来更加简洁。 - Tom

1

defaultdict 对于这种情况非常有用。

from collections import defaultdict
for line in myfile:
    # tokenize
    word_counts = defaultdict(int)
    for word in line:
        if word in hotwords:
            word_counts[word] += 1
    print '\n'.join('%s: %s' % (k, v) for k, v in word_counts.items())

是的-只是稍微调整了一下,但逻辑很好-我更喜欢这个方法而不是计数器解决方案。为每行文本文件创建一个defaultdict最有效吗? - bhalsall
@bhalsall:你可以在每行之后调用 word_counts.clear() 而不是每次创建一个新的 defaultdict。 - jfs

0

你需要对它进行标记吗?你可以对每个单词的每一行使用count()

hotwords = {'tweet':[], 'twitter':[]}
for line in file_obj:
    for word in hotwords.keys():
        hotwords[word].append(line.count(word))

否则你最终会计算子字符串。如果热词是“sex”,我不希望Middlesex被计算。 - Steve Mayne
那是正确的做法。理想情况下,我需要将每一行重新标记为单词。我不能只从头开始将其标记为单词,因为这样我就无法保留换行符(这是分隔每个推文的内容)...然后我最终会对整个文本文件计算单词频率,而不是每行的频率。 - bhalsall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接