我有以下代码,但是我无法在数据文件中修剪和存储数据:
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
...
对于每个具有递增整数的单词都是一行。
有人知道如何以这种方式保存我的数据吗?
答案 0 :(得分:2)
错误的原因是output.write
接受字符串,而不是list
。 word_features
是list
。
要将列表写入文件,您需要迭代它:
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]))
答案 1 :(得分:1)
您正在尝试将列表对象写入文件,但它需要一个字符串。你可以在这里使用`enumerate:
word_features = get_word_features(get_words_in_tweets(tweets))
with open('wordFeatures.csv', 'w') as output:
for ind, item in enumerate(word_features, 1):
output.write("{}:{}\n".format(ind, item))
或使用csv
模块:
import csv
word_features = get_word_features(get_words_in_tweets(tweets))
with open('wordFeatures.csv', 'w') as output:
writer = csv.writer(output, delimiter=':')
writer.writerows(enumerate(word_features, 1))
<强>输出:强>
1:this
2:amazing
3:car
4:concert
5:forward
6:looking
7:love
8:not
9:the
10:view
答案 2 :(得分:0)
在Python中,我将数据保存到csv文件中,但是以一种相当黑客的方式:
首先,我将数据保存到文本文件中。在每一行中,我用逗号分隔每个“列元素”。
然后,当我完成该行[当前只是文本文件中的一行]时,我会写一个新行并开始写入下一行数据。根据需要重复。
然后,当我完成后,我将文本文件重命名为csv文件。
对于你来说,添加增加的整数,你可以组成一个增量计数器。如果你按照我的方式做,你可以递增计数器,将值写入文本文件,写入逗号,写入数据,然后写入新行,然后重复。只需记住在完成所有操作后将文件重命名为csv文件。
就像我说的那样,一种破解方式,但无论如何。我愿意听取更好的方法。