这是我第一次在 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})]
most_common
,比如c.most_common(10)
,来获取计数器中出现频率最高的前10个单词。 - razpeitia