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

为何文件中存在目标单词时我的Python代码仍返回0且不输出未找到提示

问题原因分析
  • 类型匹配逻辑错误:response.split()返回的是列表类型,代码直接用if letters in line判断列表是否存在于字符串line中,该判断逻辑永远返回False,所以count不会累加,始终为0。
  • 未找到提示的逻辑错误:判断count < 1的代码放在了匹配成功的分支内部,只有匹配到内容才会进入该分支,此时count已经完成+1操作,不可能满足小于1的条件,因此永远不会输出"not found"。同时该判断应该放在遍历完全部文件行之后再执行,放在循环内没有意义。
修复后代码

如果需求为统计包含用户输入的单个单词的行数:

response = input('Please enter words: ')
target_word = response.strip()

count = 0

with open("alice.txt", "r", encoding="utf-8") as program:
    for line in program:
        # 如需大小写不敏感匹配,可改为 if target_word.lower() in line.lower()
        if target_word in line:
            count += 1

if count < 1:
    print("not found")
print(count)

如果需求为支持用户输入多个单词,统计包含任意一个输入单词的行数,可调整为:

response = input('Please enter words: ')
target_words = response.split()

count = 0

with open("alice.txt", "r", encoding="utf-8") as program:
    for line in program:
        if any(word in line for word in target_words):
            count += 1

if count < 1:
    print("not found")
print(count)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:06:08