Python 来自 txt 文件的计数器

Python Counter from txt file

我想从一个包含词频计数的文本文件中初始化一个 collections.Counter 对象。也就是说,我有一个文件 "counts.txt":

rank  wordform         abs     r        mod
   1  the           225300    29   223066.9
   2  and           157486    29   156214.4
   3  to            134478    29   134044.8
...
 999  fallen           345    29      326.6
1000  supper           368    27      325.8

我想要一个计数器对象 wordCounts 这样我就可以调用

>>> print wordCounts.most_common(3)
[('the', 225300), ('of', 157486), ('and', 134478)]

什么是最有效的 Pythonic 方式

import collections.Counter

words = dict()
fp = open('counts.txt')

for line in fp:
   items = line.split()
   words[items[1].strip()] = int(items[2].strip())

wordCounts = collections.Counter(words)

这里有两个版本。第一个将您的 counts.txt 作为常规文本文件。第二个将其视为 csv 文件(这就是它的样子)。

from collections import Counter

with open('counts.txt') as f:
    lines = [line.strip().split() for line in f]
    wordCounts = Counter({line[1]: int(line[2]) for line in lines[1:]})
    print wordCounts.most_common(3)

如果您的数据文件被某些一致的字符或字符串分隔,您可以使用 csv.DictReader 对象来解析文件。

下面显示了它是如何完成的如果你的文件是TAB定界的。

数据文件(由我编辑,以制表符分隔)

rank    wordform    abs r   mod
1   the 225300  29  223066.9
2   and 157486  29  156214.4
3   to  134478  29  134044.8
999 fallen  345 29  326.6
1000    supper  368 27  325.8

密码

from csv import DictReader
from collections import Counter

with open('counts.txt') as f:
    reader = DictReader(f, delimiter='\t')
    wordCounts = Counter({row['wordform']: int(row['abs']) for row in reader})
    print wordCounts.most_common(3)