第一次张贴在堆栈-总是发现以前的问题能够解决我的问题!我的主要问题是逻辑。。。即使是伪代码答案也不错。在
我使用python从文本文件的每一行读取数据,格式如下:
This is a tweet captured from the twitter api #hashtag http://url.com/site
使用nltk,我可以通过行标记化然后可以使用读者.sents()迭代等:
^{pr2}$但是我想计算每行的某些“热词”(存储在数组或类似的数组中)的频率,然后将它们写回文本文件。如果我用读卡器.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})]
你需要标记它吗?您可以在每一行中为每个单词使用^{} 。在
defaultdict
是这类事情的朋友。在此脚本适用于Python2.7+
相关问题 更多 >
编程相关推荐