gpt4 book ai didi

python - 用标题中的特定值划分第 2 列

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:51:06 25 4
gpt4 key购买 nike

大家好, 首先,我是编码的新手,现在正在学习。所以,请原谅我的疑惑!

我的数据如下:

TOPIC:  1 87187.0

Mr 2288.0
's 1633.0
@card@ 1132.0
party 731.0
say 710.0

TOPIC: 2 97854.0

say 2170.0
@card@ 1872.0
people 1078.0
police 562.0

等等....直到主题 100 具有相同的格式。

此处第一行是主题编号及其权重。以下是该主题中的单词及其在该主题中的权重。

我想找出每个单词的概率。那就是将每个单词的权重除以它各自的主题权重。例如,

In topic 1, the word Mr weight is 2288.0 and it's topic weight is 87187.0. So, the probability of the word Mr in Topic 0 is 2288.0/87187.0. Likewise I would like to know the probability of all the words. 

My output should be like:

TOPIC: 1 87187.0

Mr 0.02624
's 0.01872
@card@ 0.0129

等等...这些值是单词权重/主题权重的结果。

如果是正常的列划分,我会使用 col2/col1 技术,但这非常具有挑战性。所以,请指导我。提前致谢!

最佳答案

您根本没有说明您希望输出格式是什么样子,甚至没有给出这样的示例,但这至少应该为您指明正确的方向...

建议的 python 起点,除了浮点舍入问题之外,您的编辑似乎表明您想要的输出:

divisor = 1.0
with open("input.txt") as fd:
for line in fd:
fields = line.strip().split()
if len(fields) > 0:
if fields[0] == 'TOPIC:':
divisor = float(fields[-1])
if len(fields) == 2:
fields[-1] = str(float(fields[-1]) / divisor)
print ' '.join(fields)

使用上面的示例输入,此代码生成:

TOPIC: 1 87187.0

Mr 0.0262424444011
's 0.0187298565153
@card@ 0.0129835870026
party 0.00838427747256
say 0.00814341587622

TOPIC: 2 97854.0

say 0.0221758947003
@card@ 0.0191305414188
people 0.0110164122059
police 0.00574325014818

关于python - 用标题中的特定值划分第 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31392668/

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