我有个问题要做一个“output.txt”。 我想把word和prob(l.19)结果都写进 一个“output.txt”文件。 当我写“model_file.write(word,prob)”时,终端会用 “TypeError:函数只接受1个参数(给定2个)”消息。 我试图增加更多的论点,但没有成功。。 有谁能帮我提个问题吗??
这是单词COUNT.PYtotal_count = 0
train_file = open(sys.argv[1],"r")
for line in train_file:
words = line.strip().split(" ")
words.append("</s>")
for word in words:t
counts[word] = counts.get(word, 0) + 1
total_count = total_count + 1
model_file = open('output.txt',"w")
for word, count in sorted(counts.items(),reverse=True):
prob = counts[word]*1.0/total_count
print "%s --> %f" % (word, prob)
model_file.write(word, prob)
model_file.close()
#
您可以使用
print
语句执行以下操作:只是简单的替换
model_file.write(word, prob)
与
model_file.write(word+' '+str(prob)+'\n')
请注意,方法
write()
的实现只接受一个字符串参数,因此必须将prob
转换为字符串(通过方法str()
),然后通过字符串运算符+
将其与word
组合,这样就只得到一个字符串参数。注:虽然你没有问这个问题,但我不得不说,如果你要写每个单词及其概率,你应该把
model_file.write(word+' '+str(prob)+'\n')
放入for
语句中。否则,如果出于某种目的拒绝在for
语句之外调用它,那么也应该在for
语句之外分配word
和prob
。否则会导致另一个错误。相关问题 更多 >
编程相关推荐