我有以下运行良好的代码,但我无法在数据文件中修剪和存储数据:
import nltk
tweets = [
(['love', 'this', 'car']),
(['this', 'view', 'amazing']),
(['not', 'looking', 'forward', 'the', 'concert'])
]
def get_words_in_tweets(tweets):
all_words = []
for (words) in tweets:
all_words.extend(words)
return all_words
def get_word_features(wordlist):
wordlist = nltk.FreqDist(wordlist)
word_features = wordlist.keys()
return word_features
output = open('wordFeatures.csv','w')
word_features = get_word_features(get_words_in_tweets(tweets))
print (word_features)
output.write(word_features)
#print (wordlist)
output.close()
它所做的是,它检查单词是否是双重或三重等,并且只在列表中添加一个单词。 输出如下所示:
['this', 'amazing', 'car', 'concert', 'forward', 'looking', 'love', 'not', 'the', 'view']
现在如您所见,我试图将这些数据保存在文本文件中,但我得到了一个
TypeError: expected a character buffer object
我希望数组中的数据采用以下格式的文本文件:
1:this
2:amazing
3:car
4:concert
5:forward
...
所以每个单词一行,整数递增。
有人知道如何以这种方式保存我的数据吗?
最佳答案
错误的原因是output.write
接受的是字符串,而不是list
。 word_features
是一个列表
。
要将列表写入文件,您需要对其进行迭代:
for feature in word_features:
output.write("{0}\n".format(feature))
我不明白你需要的格式,因为 car
和 concert
出现在同一条线上。我假设这是一个错字,你实际上需要它们在不同的行上。然后你可以这样做以获得输出:
for nfeature in enumerate(word_features):
output.write("{0}:{1}\n".format(nfeature[0] + 1, nfeature[1]))
关于Python 将 csv 数据导出到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813490/