Python 将 csv 数据导出到文件中

标签 python csv

我有以下运行良好的代码,但我无法在数据文件中修剪和存储数据:

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接受的是字符串,而不是listword_features 是一个列表

要将列表写入文件,您需要对其进行迭代:

for feature in word_features: 
    output.write("{0}\n".format(feature))

我不明白你需要的格式,因为 carconcert 出现在同一条线上。我假设这是一个错字,你实际上需要它们在不同的行上。然后你可以这样做以获得输出:

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/

相关文章:

python - 如何在 Python Selenium 中实现类似 TestNG 的功能或在一个测试套件中添加多个单元测试?

python - 如何阻止在py2exe中编译的Python程序显示ImportError : No Module names 'ctypes'

arrays - 如何将 csv 中的特定元素存储到变量中?

PHP - 在自定义 WordPress 数据库中上传 CSV 数据

javascript - 从 API 结果导出 CSV 在 Firefox JavaScript 上不起作用

python - 从多个字典写入单个 CSV 文件

python - 将 tastypie 导入到项目中

python - Python sklearn 中的训练集

r - 计算csv文件中每个字段的最大长度

Python 对数据帧进行采样