如何创建一个for循环,将列表中的元素与字典中包含的列表中的元素进行检查?

2024-10-03 19:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为一系列网页标题分配一个主题/类别。我想先创建一个包含我需要的所有页面标题的列表,然后创建一个由主题及其相关单词组成的字典(这将是一个以列表作为值,以主题名称作为键的字典)

接下来,我想填充一个表,或者简单地以表格格式返回输出,这样我就可以在Excel中操作它,并且输出应该在一列中有页面标题,在另一列中分配主题。你能帮我完成这项任务吗

下面我提供一个列表和字典的示例

page_titles = [ "How to measure insulin", "Advice for general practitioners", "Medications for HIV"]

topic_terms = { "diabetes" : ["insulin", "sugar"], "HIV" : ["HIV", "medication for HIV"] }

Tags: 名称网页标题主题列表for字典格式
2条回答
to_write = []
for title in page_titles:    
    for topic, rel_words in topic_terms.items():
        for word in rel_words:
            if word in title:
                to_write.append((title, topic))

tou write将是一个元组列表,其中第一项是标题,第二项是主题。用它写出你的excel表格

不是很有效率,但它应该起作用

outputlist = []

for page_title in page_titles:
    for topic in topic_terms:
        for keyword in topic_terms[topic]:
            if keyword in page_title:
                outputlist.append([page_title, topic])

相关问题 更多 >