大家好,这是我试图运行的代码。我不是计算机科学家,我知道这是一个简单的答案我只是没有工具来回答它。我试图将此列表打印到文本文件。如果我打印到屏幕,它的工作原理。我得到的错误是:“TypeError:期望一个字符缓冲区对象”
这是代码
input = open('Tyger.txt', 'r')
text = input.read()
wordlist = text.split()
output_file = open ('FrequencyList.txt','w')
wordfreq = [wordlist.count(p) for p in wordlist]
#Pair words with corresponding frequency
dictionary = dict(zip(wordlist,wordfreq))
#Sort by inverse Frequency and print
aux = [(dictionary[key], key) for key in dictionary]
aux.sort()
aux.reverse()
for a in aux: output_file.write(a)
谢谢!
答案 0 :(得分:4)
正如我在上面的评论中所说,将output_file.write(a)
更改为output_file.write(str(a))
。当您print
某事时,Python会尝试对您正在打印的内容进行隐式字符串转换。这就是为什么print
一个元组(就像你在这里所做的那样)有效的原因。 file.write()
没有隐式转换,因此您必须使用str()
自行转换。
正如对此答案的评论中所述,您可能需要在文件上调用.close()
。
答案 1 :(得分:0)
您可以编写如下代码:
input = open('tyger.txt','r').read().split()
......
.........
............
for a in aux:
output_file.write(str(a))
output_file.close()
你必须close()
一个你要打开的文件,否则你将无法使用该文件。