首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python和nGrams

Python和nGrams
EN

Stack Overflow用户
提问于 2017-08-14 15:03:46
回答 2查看 362关注 0票数 0

这里的Aster用户试图完全移到python进行基本的文本分析。我试图使用nltk或其他模块在Python中复制ASTER ngram的输出。我需要能够这样做的纳克1到4。输出到csv。

数据:

代码语言:javascript
复制
Unique_ID, Text_Narrative

需要输出:

代码语言:javascript
复制
Unique_id, ngram(token), ngram(frequency)

示例输出:

  • 023345 "I“1
  • 023345“爱”1
  • 023345 "Python“1
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-14 15:23:58

出于教育原因,我只在python的标准库中编写了这个简单的版本。

生产代码应该使用spacypandas

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2017-11-10 23:32:24

正如其他人说的,这个问题确实很模糊,但既然你是新来的,这里有一个很长的形式指南。:-)

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45677519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档