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

如何修改Python关键词匹配代码以调整输出格式?

调整关键词搜索输出格式的Python代码修改建议

Hey there! Let's tweak that code to get exactly the output format you want. Here's a step-by-step breakdown with the modified code:

原始代码(Chris_Rands提供)

sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".")
search_keywords=['mother','sing','song']
for sentence in sentences:
    print("{} key words in sentence:".format(sum(1 for word in search_keywords if word in sentence)))
    for word in search_keywords:
        if word in sentence:
            print(word)
    print(sentence + "\n")

原始输出

2 key words in sentence:
sing
song
My name is sing song

1 key words in sentence:
mother
I am a mother

0 key words in sentence:

I am happy

2 key words in sentence:
sing
mother
You sing like my mother

期望输出

2 key words in sentence: sing song My name is sing song
1 key words in sentence: mother I am a mother
0 key words in sentence: I am happy
2 key words in sentence: sing mother You sing like my mother

修改后的代码

sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".")
search_keywords = ['mother','sing','song']

for sentence in sentences:
    # 清理句子前后空白,跳过split产生的空字符串
    cleaned_sentence = sentence.strip()
    if not cleaned_sentence:
        continue
    
    # 收集当前句子中匹配的关键词
    matched_words = [word for word in search_keywords if word in cleaned_sentence]
    keyword_count = len(matched_words)
    
    # 构建一行输出的各个部分
    output_components = [f"{keyword_count} key words in sentence:"]
    if keyword_count > 0:
        output_components.append(' '.join(matched_words))
    output_components.append(cleaned_sentence)
    
    # 拼接并打印整行内容
    print(' '.join(output_components))

代码修改说明

  1. 清理句子内容:用strip()去除句子前后的空格,同时跳过split(".")后可能产生的空字符串(原句子末尾的句号会导致最后一个元素为空)。
  2. 收集匹配关键词:用列表推导式一次性找出所有匹配的关键词,比原代码的循环打印更高效,也方便后续拼接。
  3. 统一一行输出:把数量、匹配关键词(如果有)、句子放在一个列表里,用' '.join()拼接成整行,完美匹配你想要的格式。
  4. 处理0关键词场景:当没有匹配关键词时,只输出数量和句子,不会出现多余的空白。

运行修改后的代码,就能得到你期望的输出结果啦!

内容的提问来源于stack exchange,提问作者Tao Song

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:09:01