我有以下代码运行良好,但我无法在数据文件中修剪和存储数据:
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
...
所以每个单词都有一行,整数递增。
有人知道如何以这种方式保存我的数据吗?