字典问题:属性错误:'str'对象没有属性'items'



问题我有这样的代码:

def _score_sentences(tf_idf_matrix) -> dict:
sentenceValue = {}
for sent, f_table in tf_idf_matrix.items():
total_score_per_sentence = 0
count_words_in_sentence = len(f_table)
for word, score in f_table.items():
total_score_per_sentence += score
sentenceValue[sent] = round(total_score_per_sentence / count_words_in_sentence, 3)
return sentenceValue
sentence_scores = _score_sentences(tf_idf_matrix)

基本上,它应该创建一个字典,每个句子都有一个浮动分数(取自tf_idf_matrix(。它打印出一些看起来像字典的东西,但当我运行这段代码时:

top_scores = {}
for sent, score in sentence_scores.items():
if f_table >= .4:
top_scores[sent] = score
print(top_scores)

我收到这个错误报告:

AttributeError                            Traceback (most recent call last)
<ipython-input-50-2220086aa6aa> in <module>
1 top_scores = {}
2 
----> 3 for sent, score in sentence_scores.items():
4     if f_table >= .4:
5         top_scores[sent] = score
AttributeError: 'str' object has no attribute 'items'

部分解决方案

我看到了一些关于这方面的其他问题,建议尝试使用ast.literal_eval()。然而,当我尝试时

import ast
d = ast.literal_eval(sentence_scores)
top_scores = {}
for sent, score in d.items():
if f_table >= .4:
top_scores[sent] = score
print(top_scores)

我收到这个错误报告:

Traceback (most recent call last):
File "c:users...interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-51-3d124b40f0bb>", line 3, in <module>
d = ast.literal_eval(sentence_scores)
File "c:users...libast.py", line 59, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "c:users...libast.py", line 47, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 1
P's grandfather
^
SyntaxError: EOL while scanning string literal

抱歉问题太长;我想在问题和解决问题的尝试中尽可能清楚。基本上,我想知道sentence_scores是否是一个字符串。如果是,我想知道为什么ast.literal_eval()不起作用。如果sentence_scores是一本字典,我想知道为什么我会得到首字母AttributeError

提前感谢!

类型检查应该会清除这个问题。我没有足够的上下文来判断你的代码是否被正确使用,但添加了更好的类型注释:

from typing import Dict
def _score_sentences(tf_idf_matrix: Dict[str, Dict[str, float]]) -> Dict[str, float]:
sentence_value: Dict[str, float] = {}
for sent, f_table in tf_idf_matrix.items():
total_score_per_sentence = 0.0
count_words_in_sentence = len(f_table)
for word, score in f_table.items():
total_score_per_sentence += score
sentence_value[sent] = round(total_score_per_sentence / count_words_in_sentence, 3)
return sentence_value
sentence_scores = _score_sentences(tf_idf_matrix)

然后运行mypy——这会告诉你问题出在哪里。我的直觉是,可能有什么东西正在覆盖代码中的sentence_scores

相关内容

最新更新