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

Python3 文本内容匹配功能实现异常求助

Fix: Script Spams "doesn't work" When Inputting "test"

Hey there! Let's get this sorted out. The issue you're seeing—9 repeated "doesn't work" messages—happens because your script is probably looping through individual characters (or hidden lines/whitespace) of the file instead of checking if your input matches the entire file content in one go.

What's Likely Wrong with Your Code

Chances are your script looks something like this (the problematic version):

from tkinter import simpledialog

with open("test.txt", "r") as f:
    user_input = simpledialog.askstring("Input", "Enter test:")
    # This loops through every character in the file (including hidden whitespace)
    for item in f.read():
        if user_input == item:
            print("works")
        else:
            print("doesn't work")

Since your file has the word "test" plus maybe invisible line breaks or spaces that add up to 9 total characters, the loop runs 9 times—each time comparing your full input to a single character, hence 9 "doesn't work" outputs.

Fixed Code

Here's the corrected version that checks your input against the full file content properly:

from tkinter import simpledialog

# Open the file and read its entire content
with open("test.txt", "r") as f:
    # Strip() removes extra whitespace (like newlines) from start/end
    file_content = f.read().strip()
    user_input = simpledialog.askstring("Input", "Enter your word:")
    
    # Compare the cleaned input to the cleaned file content
    if user_input.strip() == file_content:
        print("works")
    else:
        print("doesn't work")

Key Fixes Explained

  1. Read the entire file at once: f.read() grabs all content instead of splitting it into individual characters or lines.
  2. Clean up whitespace: .strip() removes any accidental newlines or spaces from both the file content and user input—this prevents matches from failing due to invisible characters you might not see in the file.
  3. Single comparison instead of loop: We only check once if the input matches the full file content, so you'll get exactly one output line, not multiple.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:19:05