write()接受2个位置参数,但给出了3个 [英] write() takes 2 positional arguments but 3 were given

查看:49
本文介绍了write()接受2个位置参数,但给出了3个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 print()函数在屏幕上打印它们时,我的程序可以正确产生所需的结果:

My program produces the desired results correctly as I print them on the screen using the print() function:

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 ('------------------------------')

我想将结果以准确的格式写入文本文件.我尝试了这个:

I want to write the results with the exact format to a text file though. I tried with this:

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个

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

推荐答案

print()采用单独的参数,而 file.write() 则没有.您可以重复使用 print()改为写入您的文件:

print() takes separate arguments, file.write() does not. You can reuse print() to write to your file instead:

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(),直接在字典上循环也可以.

I also used the built-in open(), there is no need to use the older and far less versatile codecs.open() in Python 3. You don't need to call .keys() either, looping over the dictionary directly also works.

这篇关于write()接受2个位置参数,但给出了3个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆