如何在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
- Flatten & Deduplicate Keywords: We first gather all unique keywords from every category that matches the query. Using a
setensures we don't print duplicate entries (even if a keyword appears in multiple categories, likeornamentin bothholidaysandsubject). - 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
相关产品推荐
相关产品推荐

