gpt4 book ai didi

python - 如何更改字典中的列表?

转载 作者:行者123 更新时间:2023-12-01 09:15:01 25 4
gpt4 key购买 nike

我制作了一个解析器,用于从过去的试卷中提取问题,并列出这些年来特定问题/主题出现的频率。它将问题/主题存储为字典,将日期存储为列表,并且应该将两者组合如下:

questions = {'Question1':['April 2011', 'May 2016'], 'Question2': ['June 2013']}

问题是,我无法更新字典中的日期列表。我的代码片段如下:

def extract_topics_dates(file):
corpus = ''
topics = []
questions = {}
year = []
pdf_reader = PyPDF2.PdfFileReader(open(file, 'rb'))
for page in pdf_reader.pages:
#For each page, get corpus of text.
for line in page.extractText().splitlines():
corpus = corpus + line

#For each page, extract topics.
for i in [phrase for phrase in map(str.strip, re.split('\d+\s\s', corpus)) if phrase]:
topics.append(extract_topic(i))
topics = [x for x in topics if x is not None]

#For each page, extract date.
year = set([x for x in year if x is not None])
year.add(get_date(page))

#For each page, now combine the topic + date.
for i in topics:
questions[i].add(year)

return questions

此函数中的所有内容都按预期工作,除了最后一个 questions[i].add(year) ,它返回 KeyError。我哪里出错了?

最佳答案

在向字典中添加任何内容之前,您应该在字典中为您的键创建一个列表。请将 for 循环 更改为以下内容:

for i in topics:
if i not in questions:
questions[i] = list()
questions[i].append(year)

或者,按照 @Jon Clements 的建议:

for topic in topics:
questions.setdefault(topic, []).append(year)

关于python - 如何更改字典中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51347844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com