Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

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

I am starting with some python task, I am facing a problem while using gensim. I am trying to load files from my disk and process them (split them and lowercase() them)

The code I have is below:

dictionary_arr=[]
for file_path in glob.glob(os.path.join(path, '*.txt')):
    with open (file_path, "r") as myfile:
        text=myfile.read()
        for words in text.lower().split():
            dictionary_arr.append(words)
dictionary = corpora.Dictionary(dictionary_arr)

The list (dictionary_arr) contains the list of all words across all the file, I then use gensim corpora.Dictionary to process the list. However I face a error.

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

I cant understand whats a problem, A little guidance would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In dictionary.py, the initialize function is:

def __init__(self, documents=None):
    self.token2id = {} # token -> tokenId
    self.id2token = {} # reverse mapping for token2id; only formed on request, to save memory
    self.dfs = {} # document frequencies: tokenId -> in how many documents this token appeared

    self.num_docs = 0 # number of documents processed
    self.num_pos = 0 # total number of corpus positions
    self.num_nnz = 0 # total number of non-zeroes in the BOW matrix

    if documents is not None:
        self.add_documents(documents)

Function add_documents Build dictionary from a collection of documents. Each document is a list of tokens:

def add_documents(self, documents):

    for docno, document in enumerate(documents):
        if docno % 10000 == 0:
            logger.info("adding document #%i to %s" % (docno, self))
        _ = self.doc2bow(document, allow_update=True) # ignore the result, here we only care about updating token ids
    logger.info("built %s from %i documents (total %i corpus positions)" %
                 (self, self.num_docs, self.num_pos))

So ,if you initialize Dictionary in this way, you must pass documents but not a single document. For example,

dic = corpora.Dictionary([a.split()])

is OK.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...