如何修复“ int”对象在TF-IDF freqDict_list中不可迭代

时间:2019-07-17 00:28:55

标签: python python-3.x tf-idf

我目前正在用python编写TF-IDF程序。我遵循了this的代码,但是没有用。

问题是'int'对象不可迭代。

Traceback (most recent call last):
  File "C:/Users/Try Arie/PycharmProjects/TF-IDF/tf-idf.py", line 106, in <module>
    TF_scores = computeTF(doc_info, freqDict_list)
  File "C:/Users/Try Arie/PycharmProjects/TF-IDF/tf-idf.py", line 67, in computeTF
    for k in tempDict['freq_dict']:
TypeError: 'int' object is not iterable

我还没有尝试任何操作,因为我只是按照链接中的代码进行操作。

def create_freq_dict(sents):
    i = 0
    freqDict_list = []
    for sent in sents:
        i += 1
        freq_dict = {}
        words = word_tokenize(sent)
        for word in words:
            word.lower()
            if word in freq_dict:
                freq_dict[word] += 1
            else:
                freq_dict = 1
            temp = {'doc_id': i, 'freq_dict': freq_dict}
        freqDict_list.append(temp)
    return freqDict_list

def computeTF(doc_info, freqDict_list):
    TF_scores = []
    for tempDict in freqDict_list:
        id = tempDict['doc_id']
        for k in tempDict['freq_dict']:
            temp = {'doc_id': id,
                    'TF_score': tempDict['freq_dict'][k]/doc_info[id-1]['doc_length'],
                    'key': k}
            TF_scores.append(temp)
    return TF_scores

我希望输出是这样的:

enter image description here

1 个答案:

答案 0 :(得分:2)

更新此行

for k in range(tempDict['freq_dict']):