问题原因是有些单词没有在任何文本中出现,导致word_in_docs为0,从而出现了除以0的错误。可以在计算TF-IDF权重时加入判断语句,如果单词在所有文本中都没有出现,则将其IDF值设为0。

修改后的代码如下:

定义一个函数,用于计算TF-IDF权重

def compute_tf_idf(text): # 对文本进行预处理 text = preprocess_text(text) # 将文本分词 words = text.split() # 计算每个单词在文本中出现的次数 word_counts = Counter(words) # 计算文本中单词的总数 total_words = len(words) # 计算每个单词在文本中出现的频率 word_freqs = {word: count/total_words for word, count in word_counts.items()} # 定义一个空字典,用于存储每个单词的TF-IDF权重 tf_idf = {} # 计算每个单词的TF-IDF权重 for word in word_freqs: # 计算单词在所有文本中出现的次数 word_in_docs = sum(1 for doc in documents if word in doc) # 如果单词在所有文本中都没有出现,则将其IDF值设为0 if word_in_docs == 0: idf = 0 else: # 计算单词的IDF值 idf = math.log(len(documents)/word_in_docs) # 计算单词的TF-IDF权重 tf_idf[word] = word_freqs[word] * idf return tf_idf

运行修改后的代码可以得到正确的输出结果

# 导入必要的库import reimport mathfrom collections import Counter# 定义一个函数用于对文本进行预处理def preprocess_texttext # 将文本中的标点符号、数字、空格等非文字字符替换为空格 text = resubr^wstext text = resubrd+text text = resubrs+ t

原文地址: https://www.cveoy.top/t/topic/heRF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录