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

终端下划线转空格方法及Hangman游戏空格显示bug修复咨询

问题解答

1. 终端中将下划线转换为空格的方法

如果是处理单行文本,可使用以下命令:

  • 用sed替换:
echo "hello_world_example" | sed 's/_/ /g'
  • 用awk替换:
echo "hello_world_example" | awk '{gsub(/_/," "); print}'

如果要直接修改文件内容(覆盖原文件):

sed -i 's/_/ /g' target_file.txt

2. Hangman游戏代码的bug修复

你的代码存在两个关联问题:空格被转为下划线、猜中所有字母后循环不终止,以下是修复后的代码和说明:

修复后的完整代码

import random

words = ["motherboard", "central processing unit", "power supply", "monitor", "graphics processing unit", "memory", "solid state drive", "mango"]
word = random.choice(words)
guessed_letters = []
incorrect_guesses = 0
max_attempts = 6 

while incorrect_guesses < max_attempts:
    # 核心修改:空格直接保留,非空格字符再判断是否已猜测
    display_word = ''.join(letter if letter == ' ' or letter in guessed_letters else '_' for letter in word)
    print(f"Word: {display_word}")

    if display_word == word:
        print("恭喜!你猜对了单词!")
        break
    print(f"剩余错误猜测次数: {max_attempts - incorrect_guesses}")
    guess = input("输入一个字母: ").lower()

    if len(guess) != 1 or not guess.isalpha():
        print("请输入单个字母。")
        continue

    if guess in guessed_letters:
        print("你已经猜过这个字母了。")
        continue

    guessed_letters.append(guess)

    if guess not in word:
        incorrect_guesses += 1
        print(f"哎呀!'{guess}'不在单词里。")
    if incorrect_guesses == max_attempts:
        print(f"抱歉,你用完了所有猜测次数。正确单词是'{word}'。")

关键修复点

  1. 保留空格不转为下划线:修改display_word的生成逻辑,判断字符为空格时直接保留,仅将未猜测的字母替换为下划线。
  2. 解决猜中后不终止的问题:因为空格现在正确保留,当所有字母都被猜中时,display_word会与原单词完全匹配,触发break终止循环。
  3. 额外优化:移除了words列表中"mango"末尾的多余空格,避免无效空格导致的匹配异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:40:16