【问题标题】:How to create a for loop that checks an element of a list against an element of a list contained in a dictionary?如何创建一个 for 循环来检查列表元素与字典中包含的列表元素?
【发布时间】:2019-12-10 10:49:38
【问题描述】:

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

接下来,我想填充一个表格或简单地以表格格式返回输出,以便我可以在 Excel 中对其进行操作,并且输出应该在一列中包含页面标题,在另一列中分配主题。你能帮我完成这个任务吗?

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

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

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

【问题讨论】:

  • 到目前为止你尝试过什么?给我们看一些代码!
  • 你的输出应该是什么样子的?

标签: python list dictionary for-loop


【解决方案1】:

效率不高,但应该可以解决问题

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])

【讨论】:

  • 使用 Pandas,您可以将列表转换为 DataFrame 并将其导出到 csv 或 Excel。
【解决方案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))

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2012-11-09
    • 2021-03-02
    相关资源
    最近更新 更多