0

我正在对任何 .txt 文件进行霍夫曼编码,所以首先我需要分析这个文本文件。我需要阅读它,然后分析。我需要像表格一样的“退出”:


信 | 频率(后面重复多少次)| 霍夫曼代码(稍后会出现)


我开始:

 f = open('test.txt', 'r')    #open test.tx
 for lines in f:
     print lines          #to ensure if all work...

如何按字母顺序从文件中读取字符:

with open("test.txt") as f_in:
    for line in f_in:
        for char in line:
            frequencies[char] += 1

???非常感谢


Well I tried like this:
frequencies = collections.defaultdict(int)
with open("test.txt") as f_in:
    for line in f_in:
        for char in line:
            frequencies[char] += 1


 frequencies = [(count, char) for char, count in frequencies.iteritems()]
 frequencies.sort(key=operator.itemgetter(1))

但是编译器给我一个“错误”在这里输入代码

我在 for 循环中需要这个字母顺序,而不是在频率结束时......

4

3 回答 3

2

要获得您的频率表,我会使用defaultdict. 这只会遍历数据一次。

import collections
import operator

frequencies = collections.defaultdict(int)
with open(filename) as f_in:
    for line in f_in:
        for char in line:
            frequencies[char] += 1


frequencies = [(count, char) for char, count in frequencies.iteritems()]
frequencies.sort(key=operator.itemgetter(1))
于 2010-12-05T00:47:00.460 回答
0
with open('test.txt') as f: data = f.read()
table = dict((c, data.count(c)) for c in set(data))
于 2010-12-05T00:36:39.550 回答
0

我使用以下方法制作了这个解决方案collections.Counter()

import re
import collections


if __name__ == '__main__':
    is_letter = re.compile('[A-Za-z]')

    frequencies = collections.Counter()
    with open(r'text.txt') as f_in:
        for line in f_in:
            for char in line:
                if is_letter.match(char):
                    frequencies[char.lower()] += 1

    # Sort characters 
    characters = [x[0] for x in frequencies.most_common()]
    characters.sort()
    for c in characters:
        print c, '|', str(frequencies[c])

正则表达式is_letter仅用于过滤我们感兴趣的字符。它给出的输出看起来像这样。

a | 177
b | 29
c | 7
d | 167
e | 374
f | 58
g | 100
h | 44
i | 135
j | 21
k | 64
l | 125
m | 85
n | 191
o | 105
p | 34
r | 185
s | 130
t | 146
u | 34
v | 68
x | 1
y | 14
于 2013-09-11T08:14:32.530 回答