使用write()写入文本文件时出现TypeError

时间:2015-11-22 19:23:40

标签: python python-3.x text-files typeerror

我正在制作一个计算德语文本中的英语主义的程序,除了在尝试将结果输出到文本文件(在代码的底部)时,一切正常。到目前为止,这是我的代码:

read

这是我得到的错误:

from collections import Counter import os.path print('='*50) print('Welcome to the ANGLICISM COUNTER 5000') while True: print('='*50) lines, blanklines, sentences, words, setnum = 0,0,0,0,1 setname = input('Please enter setname: ') listOfAnglicisms = open('anglicisms.txt').read().split() listOfGermanWords = open('haufigste.txt').read().split() anglicisms = [] falsepositive = [] def derivatesFromAnglicism(word): return any([word.startswith(a) for a in listOfAnglicisms]) while os.path.isfile(str(setname+str(setnum)+".txt")) == True: textf = open(setname+str(setnum)+'.txt') for line in textf: line = line.lower() lines+=1 if line.startswith('\n'): blanklines+=1 else: sentences += line.count('.') + line.count('!') + line.count('?') words += len(line.split(None)) anglicisms.extend([word for word in line.split() if derivatesFromAnglicism(word)]) anglicisms = [x for x in anglicisms if x not in listOfGermanWords] setnum+=1 textf.close() print('='*50) print('Lines : ',lines) print('Blanklines : ',blanklines) print('Sentences : ',sentences) print('Words: : ',words) print('Anglicisms : ',len(anglicisms)) print('Words until anglicism : ',int(words)/len(anglicisms)-1) print('All anglicisms :\n',Counter(anglicisms)) print('='*50) while falsepositive != 'n': falsepositive = input('Please enter a false positive or "n" to continue: ') if falsepositive == 'n': pass else: while falsepositive in anglicisms: anglicisms.remove(falsepositive) print('='*50) print('Lines : ',lines) print('Blanklines : ',blanklines) print('Sentences : ',sentences) print('Words: : ',words) print('Anglicisms : ',len(anglicisms)) print('Words until anglicism : ',int(words)/len(anglicisms)-1) print('All anglicisms :\n',Counter(anglicisms)) print('='*50) results = open(setname+'.txt', 'w') results.write( ('='*50)+ '\n'+ setname+'\n'+ 'Lines : '+lines+'\n'+ 'Blanklines : '+blanklines+'\n'+ 'Sentences : '+sentences+'\n'+ 'Words: : '+words+'\n'+ 'Anglicisms : '+len(anglicisms)+'\n'+ 'Words until anglicism : '+int(words)/len(anglicisms)-1+'\n'+ 'All anglicisms :\n'+Counter(anglicisms)+'\n'+ ('='*50)+ '\n' ) results.close()

我已尝试在变量上使用str()但它没有帮助。有没有人知道如何正确使用write(),所以这个错误不会再发生?

1 个答案:

答案 0 :(得分:2)

错误消息有点令人困惑。它引用了行('='*50),但该程序实际上崩溃了

'Lines                 : '+lines+'\n'+

(但我没有计算这些线。)

lines是一个整数。所以你需要用str(...)包裹它。与您正在打印的其他整数相同。