You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现多匹配关键词与对应查询的分行展示?

Split Multiple Keyword Matches into Separate Lines

Absolutely, you can adjust your code to print each matching keyword on its own line paired with the original query. Here's how to modify your existing loop to achieve exactly what you want:

Modified Code

# Your existing code to map queries to their matching category-keywords
query_to_keywords = { query: find_matching_keywords_with_categories(query.lower(), category_to_keywords) for query in query_list }

# Updated loop to print each keyword separately
for query, category_keywords in query_to_keywords.items():
    # Flatten all unique keywords across all matching categories
    all_matching_keywords = set()
    for keywords in category_keywords.values():
        all_matching_keywords.update(keywords)
    
    # Print each keyword with the query on a new line
    for keyword in all_matching_keywords:
        print(f"{query} {{{keyword}}}")

How It Works

  1. Flatten & Deduplicate Keywords: We first gather all unique keywords from every category that matches the query. Using a set ensures we don't print duplicate entries (even if a keyword appears in multiple categories, like ornament in both holidays and subject).
  2. Print Individual Pairs: For each keyword in the flattened set, we print the original query followed by the single keyword in curly braces—matching your desired output format exactly.

Example Output

For the query 5 min crafts for kids with toilet paper, this will produce:

5 min crafts for kids with toilet paper {'paper'}
5 min crafts for kids with toilet paper {'toilet'}

If you want keywords to appear in a consistent order (like alphabetical), just sort the set before looping:

for keyword in sorted(all_matching_keywords):
    print(f"{query} {{{keyword}}}")

That’s all you need to get the output structure you’re looking for!

内容的提问来源于stack exchange,提问作者Parth Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:37:35