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

Python单词加解密功能实现求助:文件校验失败问题

Python 单词加解密函数错误修复

原代码问题分析

scramble 函数问题

你编写的scramble函数存在多处语法与逻辑错误,无法实现「加密单词后写入文件」的需求:

def scramble():
    word = open("wordlist.txt", "a")
    userword = input("Give me a word to scramble")
    newword = userword.replace("a", "*")
    newword2 = neword.replace("o", "0")  # 变量名错误:newword 误写为 neword
    word.write(userword)  # 逻辑错误:写入原单词而非加密后的 newword2
    word.write(\n)  # 语法错误:字符串未加引号,应为 "\n"
    word.close  # 语法错误:close是方法,需加括号调用 close()

unscramble 函数问题

试写的unscramble函数逻辑混乱,导致校验始终失败:

def unscramble():
    word = open("wordlist.txt", "r")
    userinput = input("Enter a word and I'll see if i have it")
    userinput2 = userinput.replace("*","a")
    userinput3 = userinput2.replace("0","o")
    for line in word:
        if userinput3 in line:
            print("Yes, I do have that word. Would you like to see it scrambled?")
        else:
            print("Sorry, I don't have that")  # 遍历每行都输出提示,只要一行不匹配就打印错误,逻辑错误

修复后的代码

修复版 scramble 函数

用with语句自动管理文件,修正变量名与写入逻辑:

def scramble():
    # with 语句自动关闭文件,避免资源泄漏
    with open("wordlist.txt", "a", encoding="utf-8") as f:
        userword = input("Give me a word to scramble: ")
        # 连续替换,无需中间变量
        scrambled_word = userword.replace("a", "*").replace("o", "0")
        # 写入加密后的单词并换行
        f.write(scrambled_word + "\n")
    print(f"已加密单词并写入文件:{scrambled_word}")

修复版 unscramble 函数

修正遍历逻辑,处理换行符,实现「输入加密单词→解密→查找匹配→输出结果」:

def unscramble():
    found = False
    user_input = input("Enter a scrambled word to check: ")
    # 解密用户输入的加密单词
    decrypted_word = user_input.replace("*", "a").replace("0", "o")
    
    with open("wordlist.txt", "r", encoding="utf-8") as f:
        for line in f:
            # 去除每行的换行符与空白字符
            scrambled_line = line.strip()
            # 解密文件中的加密单词,与用户输入的解密结果对比
            if scrambled_line.replace("*", "a").replace("0", "o") == decrypted_word:
                print(f"找到匹配单词!原单词:{decrypted_word},加密后:{scrambled_line}")
                found = True
                break  # 找到后停止遍历
    
    if not found:
        print("抱歉,未找到匹配的单词")

说明

  1. scramble函数现在会正确将原单词加密后写入文件,例如输入apple会写入*pple,输入orange会写入0r*nge
  2. unscramble函数接收加密单词,解密后匹配文件中加密单词的解密结果,找到后输出原单词与加密形式
  3. 使用with语句管理文件是Python的最佳实践,无需手动调用close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:35:18