python - 计算(和写入)文本文件中每一行的词频

标签 python loops nltk filewriter

第一次在堆栈中发帖 - 总是发现以前的问题足以解决我的问题!我的主要问题是逻辑......即使是伪代码答案也会很棒。

我正在使用 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})]

最佳答案

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+

关于python - 计算(和写入)文本文件中每一行的词频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5595574/

相关文章:

python - 编写一个 for 循环来打印 1 个嵌套字典的键

javascript - 在 Bonferroni 不等式的 JS 实现中避免多重循环

python - 过滤斯坦福依存解析器输出

python - python 和 nltk 的 Utf-8 问题

python - Django应用程序中API调用的问题

python - 在 OSX mountain lion 上使用 Homebrew 软件安装 python 2.76 的问题

python - gdfs 到图表,反之亦然

Python搜索字符串并打印它所在的文件

javascript - 更好的做法 : Eliminate the nested loops?

scikit-learn - 混淆矩阵 - 测试情感分析模型