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