简体   繁体   English

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

[英]write() takes 2 positional arguments but 3 were given

My program produces the desired results correctly as I print them on the screen using the print() function: 当我使用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 ('------------------------------')

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

but I get the error: 但是我得到了错误:

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

print() takes separate arguments, file.write() does not . print()具有单独的参数, file.write() 不具有 You can reuse print() to write to your file instead: 您可以重复使用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 ('------------------------------')

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. 我还使用了内置的open() ,无需在Python 3中使用较旧的通用性codecs.open() 。您也不需要调用.keys() ,直接在字典上循环也可以。

file.write is given multiple arguments when its expecting only one string argument file.write只需要一个字符串参数时,会被赋予多个参数

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

The error gets raised as 'stem total frequency:', s are treated as two different arguments. 误差以'stem total frequency:', s被视为两个不同的参数。 This can be fixed by concatenation 可以通过串联来解决

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

You're supplying two arguments to write on this line, when it only wants one. 当只需要一个参数时,您将提供两个参数在该行上write In contrast, print is happy to take as many arguments as you care to give it. 相比之下, print乐于接受您愿意提供的尽可能多的论据。 Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM