gpt4 book ai didi

Python,概率

转载 作者:行者123 更新时间:2023-12-01 06:13:46 30 4
gpt4 key购买 nike

接下来是我的代码:

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

list= [(count, char) for char, count in frequencies.iteritems()]

此代码打开test.txt,读取每一行并将“列表”符号放入表单中,例如:[(3, 'a'),........ .]。这意味着在整个文本文件中,有三个 a 等等...

我需要的是计算这个数字,而不是3,我需要[ 3/所有符号的数字]。所以我不需要文本中有多少个符号,例如a,但我需要符号a的概率。

因此,如果在文本(test.txt)中会有“aaab”,我需要“list”的输出:[(0.75, 'a'), (0.25, ' b')]

非常感谢您的帮助。

<小时/>

编辑2

import collections
frequencies = collections.defaultdict(int)



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

verj= [(count/total, char) for char, count in frequencies.iteritems()]

这不起作用,给我错误:

total = float(sum(frequencies.keys()))

TypeError: unsupported operand type(s) for +: 'int' and 'str'

最佳答案

如果 frequencies = {"a": 3, "b": 4}frequencies.values() 给我们 [3, 4] 我们可以计算总和:

total = float(sum(frequencies.values()))

然后是概率:

probs = [(count / total, char) for char, count in frequencies.iteritems()]

请注意,Python 在将两个整数相除时返回一个整数,这就是我首先将总和转换为 float 的原因:

Python 2.7 (r27:82508, Jul  3 2010, 21:12:11) [GCC 4.0.1 (Apple Inc. build 5493)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> 3 / 40>>> 3 / 4.00.75

关于Python,概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4422174/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com