2017-08-14 59 views
0

Aster用户在这里试图完全移动到python的基本文本分析。 我想在Python中使用nltk或其他模块复制ASTER ngram的输出。我需要能够为1到4的ngram做到这一点。输出到csv。Python和nGrams

DATA:

Unique_ID, Text_Narrative 

OUTPUT需要:

Unique_id, ngram(token), ngram(frequency) 

输出示例:

  • 023345 “I” 1
  • 023345 “爱” 1
  • 023345 “巨蟒” 1
+0

嗨,欢迎来到SO,你能包括一些你想要的代码吗?主要问题是什么? –

+0

我们不是一个编码服务。请告诉我们你做了什么以及你卡在哪里。 –

+0

你需要使用'open'或'csv.writer'作为文件写入的东西,然后我会推荐'''''''''''Counter',这就是它。你想要unique_ID字符串内的频率还是一起? –

回答

0

我写了这个简单的版本只python标准库,为教育的原因。

生产代码应使用spacypandas

import collections 
from operator import itemgetter as at 
with open("input.csv",'r') as f: 
    data = [l.split(',', 2) for l in f.readlines()] 
spaced = lambda t: (t[0][0],' '.join(map(at(1), t))) if t[0][0]==t[1][0] else [] 
unigrams = [(i,w) for i, d in data for w in d.split()] 
bigrams = filter(any, map(spaced, zip(unigrams, unigrams[1:]))) 
trigrams = filter(any, map(spaced, zip(unigrams, unigrams[1:], unigrams[2:]))) 
with open("output.csv", 'w') as f: 
    for ngram in [unigrams, bigrams, trigrams]: 
     counts = collections.Counter(ngram) 
     for t,count in counts.items(): 
      f.write("{i},{w},{c}\n".format(c=count, i=t[0], w=t[1])) 
+0

谢谢Uri-这段代码让我在中途得到了一半。你可以分享一下这样的调整:我将运行一个2字,3字等的ngram字样吗? –

+0

我已经添加了bigrams和trigrams计算,如果有帮助请接受答案。如果您有任何其他要求,请提出一个新问题 –

0

正如有人说真正的问题是模糊的,但因为你是新来的是一个漫长的形式引导。 :-)

from collections import Counter 

#Your starting input - a phrase with an ID 
#I added some extra words to show count 
dict1 = {'023345': 'I love Python love Python Python'} 


#Split the dict vlue into a list for counting 
dict1['023345'] = dict1['023345'].split() 

#Use counter to count 
countlist = Counter(dict1['023345']) 

#count list is now "Counter({'I': 1, 'Python': 1, 'love': 1})" 

#If you want to output it like you requested, interate over the dict 
for key, value in dict1.iteritems(): 
    id1 = key 
    for key, value in countlist.iteritems(): 
     print id1, key, value