write()接受2个位置参数,但给出3个

时间:2014-07-16 17:01:59

标签: python python-3.x io

当我使用print()功能在屏幕上打印时,我的程序会正确生成所需的结果:

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()需要2个位置参数但是3个被赋予

3 个答案:

答案 0 :(得分: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(),不需要在Python 3中使用较旧且功能较少的codecs.open()。您不需要调用.keys()或者,直接在字典上循环也可以。

答案 1 :(得分:2)

file.write在期望只有一个字符串参数

时会被赋予多个参数
file.write('stem total frequency:', s)
                                  ^

'stem total frequency:', s被视为两个不同的参数时,会引发错误。这可以通过连接来修复

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

答案 2 :(得分:1)

file.write('stem:', k)

当你想要一个时,你在这一行上为write提供了两个参数。相比之下,print很乐意接受尽可能多的论点。尝试:

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