【问题标题】:How to save the results from nltk function "most_informative_features" to a txt file in Python如何将 nltk 函数“most_informative_features”的结果保存到 Python 中的 txt 文件
【发布时间】:2016-03-21 04:46:24
【问题描述】:

对不起,如果这是一个菜鸟问题!我正在使用 nltk 对 python 进行情感分析。它有一个返回最多信息功能的函数,但是每当我尝试将结果保存到文本文件时,我都会收到以下错误“TypeError:必须是 str,而不是 list”。我使用的代码如下

classifier.most_informative_features(100)  

str(information)
saveFile = open('informationFile.txt', 'w')

saveFile.write(information)
saveFile.close()

任何想法我做错了什么?

【问题讨论】:

  • 错误很明显类型不兼容,要么转换成串联字符串,要么腌制它

标签: python string nltk sentiment-analysis


【解决方案1】:

您需要将从列表到字符串的转换分配给某事,或者就地执行...

saveFile.write(''.join(information))

str 应用于变量会生成一个值,但不会更改变量(除非您分配它)

>>> bar
['a', 'b', 'c']
>>> str(bar)
"['a', 'b', 'c']"
>>> bar
['a', 'b', 'c']
>>> ', '.join(bar)
'a, b, c'
>>> bar
['a', 'b', 'c']
>>> bar = ', '.join(bar)
>>> bar
'a, b, c'

【讨论】:

  • 为什么要将列表转换为str,而您可以遍历项目并编写它们或加入项目并立即编写?
  • information = classifier.most_informative_features(100) saveFile = open('informationFile.txt', 'w') saveFile.write(str(information)) saveFile.close()
  • str() 应用到一个列表会给你一个字符串,但不是你应该写入文件的字符串。使用join 或循环来正确处理。
猜你喜欢
  • 2019-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多