python - 使用 pandas 将输出写入另一个文件
问题描述
我正在使用 LDA 在文本中查找主题。
import pandas
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
n_components = 5
n_top_words = 10
def print_top_words(model, feature_names, n_top_words):
for topic_idx, topic in enumerate(model.components_):
message = "Topic %d: " % topic_idx
message += " ".join([feature_names[i]
for i in topic.argsort()[:-n_top_words - 1:-1]])
print(message)
print()
df = pandas.read_csv('text.csv', encoding = 'utf-8')
text = df['a']
data_samples = text.values.tolist()
# Use tf (raw term count) features for LDA.
tf_vectorizer = CountVectorizer()
tf = tf_vectorizer.fit_transform(data_samples)
lda = LatentDirichletAllocation(n_components=n_components, max_iter=5,
learning_method='online',
learning_offset=50.,
random_state=0)
lda.fit(tf)
print("\nTopics in LDA model:")
tf_feature_names = tf_vectorizer.get_feature_names()
print_top_words(lda, tf_feature_names, n_top_words)
我有一个很好的输出:
LDA模型中的主题:
话题0:订单未生产好收到提前退货总希望
话题一:接木色间交破转转抵坏
话题2:发货产品可能包店提前日期坏了很好
话题3:误导性产品法国模型破开书年研究会
话题四:地址提货变更发票提货遗漏请开票提前改
但我希望将此输出写入带有熊猫的 csv 文件中。
Topic 0 Topic 1 Topic 2 ...
order advance ... ...
not return ... ...
produced always ... ...
well wishes ... ...
received hello ... ...
这是可能的?
解决方案
LDA模型中的主题:
话题0:订单未生产好收到提前退货总希望
话题一:接木色间交破转转抵坏
话题2:发货产品可能包店提前日期坏了很好
话题3:误导性产品法国模型破开书年研究会
话题四:地址提货变更发票提货遗漏请开票提前改
df.to_csv("filename.csv")
推荐阅读
- google-cloud-platform - 更改 GKE 集群的 CIDR 子网
- mysql - SQL 查询计算并显示过去 12 个月的每个月的总和数据
- arrays - Excel VBA - 将数组添加到字典并搜索它是否存在
- javascript - 为什么我的网站在每个文件都成功加载后显示加载图标?
- acumatica - 为什么这个错误会在 acumatica 中刷新页面。{“消息”:“发生错误。”}
- reactjs - 在 Django 中生成可共享的链接功能?
- django - 获取与 django 模型数组字段相关的错误
- timer - 如何停止启动时设置的定时器?
- python - Python 在单个循环中将 Json 数组转换为 Excell 文件
- flutter - 无法使用静态访问访问实例成员“项目”