当我使用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()接受两个位置参数,但给出了3个
发布于 2014-07-16 09:05:26
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()
,直接遍历字典也是有效的。
发布于 2014-07-16 09:05:33
当file.write
只需要一个字符串参数时,它会被赋予多个参数。
file.write('stem total frequency:', s)
^
当'stem total frequency:', s
作为两个不同的参数处理时,会引发错误。这可以通过串联来解决。
file.write('stem total frequency: '+str(s))
^
发布于 2014-07-16 09:05:11
file.write('stem:', k)
您在这一行中向write
提供了两个参数,而它只需要一个参数。相反,print
乐于接受尽可能多的论点。尝试:
file.write('stem: ' + str(k))
https://stackoverflow.com/questions/24786613
复制