2014-07-16 34 views
0

我的程序正確地產生所期望的結果,因爲我使用print()功能打印它們在屏幕上:寫()採用2的位置參數,但被給予3

for k in main_dic.keys(): 
    s = 0 
    print ('stem:', k) 
    print ('word forms and frequencies:') 
    for w in main_dic[k]: 
     print ('%-10s ==> %10d' % (w,word_forms[w])) 
     s += word_forms[w] 
    print ('stem total frequency:', s) 

    print ('------------------------------') 

我想要寫與精確格式的結果到一個文本文件,但。我試着用這樣的:

file = codecs.open('result.txt','a','utf-8') 
for k in main_dic.keys(): 
    file.write('stem:', k) 
    file.write('\n') 
    file.write('word forms and frequencies:\n') 
    for w in main_dic[k]: 
     file.write('%-10s ==> %10d' % (w,word_forms[w])) 
     file.write('\n') 
     s += word_forms[w] 
    file.write('stem total frequency:', s) 
    file.write('\n') 
    file.write('------------------------------\n') 
file.close() 

,但我得到的錯誤:

TypeError: write() takes 2 positional arguments but 3 were given

回答

3

print()需要單獨的參數,file.write()。您可以重複print()到 寫信給你的文件,而不是:

with open('result.txt', 'a', encoding='utf-8') as outf: 
    for k in main_dic: 
     s = 0 
     print('stem:', k, file=outf) 
     print('word forms and frequencies:', file=outf) 
     for w in main_dic[k]: 
      print('%-10s ==> %10d' % (w,word_forms[w]), file=outf) 
      s += word_forms[w] 
     print ('stem total frequency:', s, file=outf) 
     print ('------------------------------') 

我還使用了內置open(),沒有必要使用舊的和少得多的多功能codecs.open()在Python 3你不需要要呼叫.keys(),直接循環字典也可以。當它的期待只有一個字符串參數

file.write('stem total frequency:', s) 
           ^

'stem total frequency:', s是作爲兩個不同的參數處理的誤差會引發

1
file.write('stem:', k) 

你在這條線提供兩個參數write,當它只想一個。相比之下,print很樂意接受盡可能多的論據,因爲你很關心它。嘗試:

file.write('stem: ' + str(k)) 
2

file.write給出多個參數。這可以通過級聯來解決

file.write('stem total frequency: '+str(s)) 
           ^
相關問題