[英]python write can take 2 arguments
我有一個問題要制作“output.txt”。 我想將 word 和 prob(l.19) 結果寫入“output.txt”文件。 當我寫“model_file.write(word, prob)”時,終端用“TypeError:函數恰好需要1個參數(給定2個)”消息罵我。 我試圖添加更多的論點,但沒有奏效.. 有人能幫我解決我的問題嗎?
這是一個字數.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()
#
只需簡單地更換
model_file.write(word, prob)
和
model_file.write(word+' '+str(prob)+'\\n')
請注意,方法write()
被實現為僅接受一個字符串參數,因此您必須將prob
轉換為字符串(通過方法str()
),然后通過字符串運算符+
將其與word
組合,以便您得到只有一個字符串參數。
PS:雖然你沒問這個,但我不得不說,如果你要寫每個單詞及其概率,你應該把model_file.write(word+' '+str(prob)+'\\n')
放入for
聲明。 否則,如果您出於某種目的拒絕在for
語句之外調用它,那么您也應該在for
語句之外分配word
和prob
。 否則會導致另一個錯誤。
您可以使用print
語句來執行此操作:
print >>model_file, word, prob
我想創建一種關於我的 df 的描述,所以我寫了這個:
# Create an empty txt
f = open(os.path.join(pathlib.Path().absolute(),'folder','florder','name.txt'), "a")
# Create an kind of header
f.write('text'+'\n')
f.write('text'+'\n')
f.write("""
-------------------
""")
f.write('text:'+ '\n')
f.write("""
""")
for c in range(0, len(df.columns)):
campo = df.columns[c]
if df[df.columns[c]].dtype== 'object':
text= 'Tex'
outfile = open('name.txt','w')
f.write('str:'+"'"+str(xxx)+"'"'\n')
f.write('str:'+ str(str)+'\n')
f.write('\n')
f.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.