Python中的频率分析以频率打印字母,而不是按频率打印数字

2024-05-19 14:42:18 发布

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

s=array1 #user inputs an array with text in it
n=len(s)
f=arange(0,26,1)
import collections
dict = collections.defaultdict(int)
for c in s:
    dict[c] += 1

for c in f:
    print  c,dict[c]/float(n)

在输出中,c是数字而不是字母,我不知道如何将其转换回字母。在

还有,有没有什么方法可以把频率/字母输入数组,这样就可以把它们绘制成直方图了?在


Tags: textinanforlenwith字母it
3条回答

如果您使用的是python2.7或更高版本,那么可以使用collections.Counter。在

Python2.7+

>>> import collections
>>> s = "I want to count frequencies."
>>> counter = collections.Counter(s)
>>> counter
Counter({' ': 4, 'e': 3, 'n': 3, 't': 3, 'c': 2, 'o': 2, 'u': 2, 'a': 1, 'f': 1, 'I': 1,     'q': 1, 'i': 1, 's': 1, 'r': 1, 'w': 1, '.': 1})
>>> n = sum(counter.values()) * 1.0   # Convert to float so division returns float.
>>> n
28
>>> [(char, count / n) for char, count in counter.most_common()]
[(' ', 0.14285714285714285), ('e', 0.10714285714285714), ('n', 0.10714285714285714), ('t', 0.10714285714285714), ('c', 0.07142857142857142), ('o', 0.07142857142857142), ('u', 0.07142857142857142), ('a', 0.03571428571428571), ('f', 0.03571428571428571), ('I', 0.03571428571428571), ('q', 0.03571428571428571), ('i', 0.03571428571428571), ('s', 0.03571428571428571), ('r', 0.03571428571428571), ('w', 0.03571428571428571), ('.', 0.03571428571428571)]

Python 3+

^{pr2}$

这还将按频率降序返回(char,frequency)元组。在

要将一个数字转换成它所代表的字母,只需使用内置的chr

>>> chr(98)
'b'
>>> chr(66)
'B'
>>> 

应该指出的是,您没有使用正确类型的参数调用map(因此TypeError)。它需要一个函数和一个或多个iterables,该函数应用于该函数。第二个参数是toChar[i],它是一个字符串。所有ITerable实现^{}。举例说明:

>>> l, t = [], ()
>>> l.__iter__
<<< <method-wrapper '__iter__' of list object at 0x7ebcd6ac>
>>> t.__iter__
<<< <method-wrapper '__iter__' of tuple object at 0x7ef6102c>

DTing's answer让我想起了collections.Counter

^{pr2}$

相关问题 更多 >