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

Scrabble单词有效性校验代码未读取字典文件问题求助

Fixing Your Scrabble Word Validation Issue

Hey there! Let's figure out why your dictionary check is always landing on that "never heard of this word" message instead of validating words correctly. I’ve spotted a couple of key issues in your code that are causing this problem:

1. The split() Mistake That Breaks Comparisons

The biggest culprit is this line:

line = line.split()

When you use split() on a single word line from your dictionary file (like "APPLE"), it turns that string into a list (e.g., ["APPLE"]). Then you’re trying to compare this list to user_word.upper()—a string. A string and a list will never be equal, so your if condition never triggers, and the code jumps straight to the final print statement.

Instead, use strip() to remove newline characters and extra whitespace, and normalize the case to match your input:

line = line.strip().upper()

2. Better File Handling (To Avoid Hidden Issues)

Right now you’re opening the file but not closing it explicitly. While Python will clean this up eventually, using a with statement ensures the file is properly closed after use, which is cleaner and avoids resource leaks:

with open("dictionary.txt", "r") as dictionary:

3. Optional: Speed Up Repeated Checks

If you’re going to validate multiple words, loading the entire dictionary into a set first makes lookups way faster (O(1) instead of looping through every line each time). Here’s the fixed and optimized version of your function:

Updated Working Code

def dictionary_check(user_word):
    # Load all valid words into a set (move this outside the function if checking multiple times)
    with open("dictionary.txt", "r") as dictionary:
        valid_words = {line.strip().upper() for line in dictionary}
    
    if user_word.upper() in valid_words:
        print("word is valid")
        return
    print("never heard of this word")

Quick Sanity Check

Double-check that dictionary.txt is in the same folder as your Python script. If it’s stored elsewhere, you’ll need to use the full file path (e.g., "/Users/you/scrabble/dictionary.txt" on macOS, or "C:\\Users\\you\\scrabble\\dictionary.txt" on Windows).

Give these changes a shot—your word validation should start working as expected!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:28:47