python write可以接受2个参数

2024-05-15 03:29:20 发布

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

我有个问题要做一个“output.txt”。 我想把word和prob(l.19)结果都写进 一个“output.txt”文件。 当我写“model_file.write(word,prob)”时,终端会用 “TypeError:函数只接受1个参数(给定2个)”消息。 我试图增加更多的论点,但没有成功。。 有谁能帮我提个问题吗??

这是单词COUNT.PY
total_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()
#

Tags: intxtforoutputmodelcounttrainopen
2条回答

您可以使用print语句执行以下操作:

print >>model_file, word, prob

只是简单的替换

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语句之外分配wordprob。否则会导致另一个错误。

相关问题 更多 >

    热门问题