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



当我使用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个给定了

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(),在Python3中不需要使用更老、功能更差的codecs.open()。您也不需要调用.keys(),直接在字典上循环也可以。

file.write在只期望一个字符串参数时被赋予多个参数

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

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

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

write只需要一个参数时,您在这一行为它提供了两个参数。相比之下,print乐于接受尽可能多的论点

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

最新更新