假设您忽略 TOPIC 行,请使用 defaultdict 对值进行分组,然后在最后进行计算:
from collections import defaultdict
from itertools import groupby, imap
d = defaultdict(list)
with open("doc1") as f,open("doc2") as f2:
values = map(float, f2.read().split())
for line in f:
if line.strip() and not line.startswith("TOPIC"):
name, val = line.split()
d[name].append(float(val))
for k,v in d.items():
print("Prob for {} is {}".format(k ,sum(i*j for i, j in zip(v,values)) ))
另一种方法是边做边计算,每次点击新部分(即带有 TOPIC 的行)时增加计数,以通过索引从值中获取正确的值:
from collections import defaultdict
d = defaultdict(float)
from itertools import imap
with open("doc1") as f,open("doc2") as f2:
# create list of all floats from doc2
values = imap(float, f2.read().split())
for line in f:
# if we have a new TOPIC increase the ind to get corresponding ndex from values
if line.startswith("TOPIC"):
ind = next(values)
continue
# ignore empty lines
if line.strip():
# get word and float and multiply the val by corresponding values value
name, val = line.split()
d[name] += float(val) * values[ind]
for k,v in d.items():
print("Prob for {} is {}".format(k ,v) )
使用你的两个 doc1 内容和0 0.566667 0 0.0333333 0
doc2 内部输出以下两者:
Prob for web is 0.085187930859
Prob for say is 0.0255701266375
Prob for online is 0.0076985327511
Prob for site is 0.0293277438137
Prob for Internet is 0.00870667394471
您还可以使用 itertools groupby:
from collections import defaultdict
d = defaultdict(float)
from itertools import groupby, imap
with open("doc1") as f,open("doc2") as f2:
values = imap(float, f2.read().split())
# lambda x: not(x.strip()) will split into groups on the empty lines
for ind, (k, v) in enumerate(groupby(f, key=lambda x: not(x.strip()))):
if not k:
topic = next(v)
# get matching float from values
f = next(values)
# iterate over the group
for s in v:
name, val = s.split()
d[name] += (float(val) * f)
for k,v in d.iteritems():
print("Prob for {} is {}".format(k,v))
对于 python3 所有迭代工具 https://docs.python.org/2/library/itertools.html imaps
应该改为仅map
它还返回 python3 中的迭代器。