TypeError: doc2bow expects an array of unicode tokens on input, not a single string

本文详细介绍了一种使用LDA(Latent Dirichlet Allocation)主题模型进行文本分析的方法,重点在于如何从原始文档中构建词典及语料库,进而训练并保存LDA模型。文章首先介绍了输入数据的正确格式——字符数组的数组,随后展示了如何通过NLTK和Gensim库读取文本数据,进行分词,并将分词后的结果存储为数据集。接着,文章演示了如何利用Gensim的Dictionary类创建词典,并将词典保存为文件,最后通过LdaModel类训练模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

构造词典时,输入的不应为原始文档集合,而是字符数组的数组。

import nltk
from gensim.models.ldamulticore import LdaModel
from gensim.corpora.dictionary import Dictionary
from gensim.test.utils import datapath
class LDA():
    def __init__(self):
        super(LDA, self).__init__()
    def getDataArray(self,src):
        file = open(src, 'r', encoding='UTF-8')
        dataset = []  # Gensim输入数据
        count=0
        for text in file.readlines():
            print(count)
            # corpus=[dictory.doc2bow(nltk.tokenize(text)) for text in file.readlines()]
            tokens = nltk.word_tokenize(text)
            dataset.append(tokens)
            count+=1
        print('Get data array complete!')
        return dataset

if __name__=="__main__":
    lda=LDA()
    path=你的文件路径
    dicFile=你的词典路径
    dataset=lda.getDataArray(path)
    dictory=Dictionary(dataset)
    dictory.save_as_text(dicFile)#词典保存为文件
    corpus=[dictory.doc2bow(text) for text in dataset]#转换为数字表示
    # 利用处理好的语料训练模型
    lda = LdaModel(corpus, num_topics=5,alpha='auto',eval_every=5)

    #save model
    temp_file=datapath('model')
    lda.save(temp_file)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值