【问题标题】:write() takes 2 positional arguments but 3 were givenwrite() 接受 2 个位置参数,但给出了 3 个
【发布时间】:2014-09-07 07:48:54
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x io


    【解决方案1】:

    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(),直接遍历字典也可以。

    【讨论】:

      【解决方案2】:

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

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

      由于'stem total frequency:', s 被视为两个不同的参数而引发错误。这可以通过串联来解决

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

      【讨论】:

        【解决方案3】:
        file.write('stem:', k)
        

        您在这一行上向write 提供了两个参数,而它只需要一个。相比之下,print 很乐意接受尽可能多的参数。试试:

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

        【讨论】:

          猜你喜欢
          • 2022-01-17
          • 2019-09-21
          • 2019-07-19
          • 2021-02-02
          • 2020-02-07
          • 2017-03-14
          • 1970-01-01
          • 1970-01-01
          • 2022-12-12
          相关资源
          最近更新 更多