首页 > 解决方案 > 使用 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     ...       ...

这是可能的?

标签: pythonpandascsv

解决方案


LDA模型中的主题:

话题0:订单未生产好收到提前退货总希望

话题一:接木色间交破转转抵坏

话题2:发货产品可能包店提前日期坏了很好

话题3:误导性产品法国模型破开书年研究会

话题四:地址提货变更发票提货遗漏请开票提前改

df.to_csv("filename.csv")


推荐阅读