如何只在一个csv文本文件/条目的每一行中找到所有ngram?

2024-03-28 10:05:46 发布

您现在位置:Python中文网/ 问答频道 /正文

from nltk import *
from collections import Counter

bigtxt = open('toSort.txt', 'r').read()
ngram_counts = Counter(ngrams(bigtxt.split(), 3))


print(ngram_counts.most_common(10))

我正在处理一个数据集,其中有多个条目(每个条目最初是csv文件中的一行,但现在是文本文件的一行):Ex

^{pr2}$

上面的第一个代码部分是我试图找到一定大小的所有n-gram(在本例中是3),但是它将文本文件中的所有行视为一个连续运行的短语(如预期的那样),从而找到所有的n-gram,甚至跨越不同的行,例如:

 jump top left 
 top left now
 left now blue
 now blue sky

各种各样的3克。在一条直线上只找到n个g并计算它们的频率的最佳方法是什么

jump top left
top left now

是有效的3克但是

now blue sky

不是吗?在


Tags: fromimporttopcounter条目blueleftnow
1条回答
网友
1楼 · 发布于 2024-03-28 10:05:46

您可以逐行读取文件,为每行分别计数ngram,然后将计数器合并在一起:

from nltk import *
from collections import Counter

ngram_counts = Counter()
with open('toSort.txt') as bigtxt:
    for l in bigtxt:
        ngram_counts.update(Counter(ngrams(l.split(), 3)))


print(ngram_counts.most_common(10))

Counter.update

Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them.

相关问题 更多 >