存储和替换列表中的单词 (Python)

Store and Replace the Word from a List (Python)

我正在尝试存储列表中的一个词,该词将被另一个词替换。存储的单词,用户将尝试猜测该单词是什么。

print("\nPlease enter the name of the file.")
filename = input()
sample=open(filename, 'r').read()
print(sample)

import random

with open ("words.txt") as w:
    words = random.sample ([x.rstrip() for x in w],9)
    grid = [words[i:i + 3] for i in range (0, len(words), 3)]
    for a,b,c in grid:
        print(a,b,c)

import time,os

time.sleep(5)
os.system('clear')

所以上面发生的事情是用户输入了包含十个不同单词的文件。不同的单词将排列在一个 grid.A 计时器中,用户需要记住该列表中的单词,一旦计时器启动,将出现另一个网格,其中一个单词已被替换。然后用户需要输入被替换的单词。

我正在努力解决的问题实际上是存储列表中将要替换的单词,以便用户可以正确输入替换后的单词。

我已经查看过替换列表中的单词等等,但我无法找到存储将被替换的单词的答案。

谢谢

如果我理解你想要实现的目标,我认为你应该使用这样的东西 words[words.index(word_to_be_replaced)] = new_word

为了回答您的问题,这里有一个示例,说明如何替换字符串,然后在您的程序中使用它。这个简短的示例仅显示一个包含九个字母的列表,其中一个已替换为 x。用户必须输入 x 所在的字母。

import random

l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

replace = random.choice(l)
l[l.index(replace)] = 'x'

print(l)
i = input("Which letter was replaced? ")

if i == replace:
    print("That's right!")
else:
    print("Nope, it was {} that got replaced!".format(replace))

很难说清楚你的代码中发生了什么,所以我用不同的风格重写了程序。您应该能够将其中一些技术合并到您自己的代码中。 /usr/share/dict/words 是一个 standard Linux file,在不同的行中包含字典单词列表。

import os
import random
import time

def print_grid(li):
    grid = [word_list[i:i+3] for i in range(0, len(word_list), 3)]
    for l in grid:
        print(''.join('{:23}'.format(i) for i in l))

if __name__ == "__main__":
    # get words
    with open('/usr/share/dict/words') as f:
        words = f.read().splitlines()

    # get nine random words, the word to replace, and a new word to replace it
    word_list = [random.choice(words) for _ in range(9)]
    replace_word = random.choice(word_list)
    new_word = random.choice(words)

    # print words in a grid, wait 5 seconds, and clear the screen
    print_grid(word_list)
    time.sleep(5)
    os.system('clear')

    # replace word, and print modified list in a grid
    word_list[word_list.index(replace_word)] = new_word
    print_grid(word_list)

    # prompt user to guess
    guess = input("Which word has been replaced? ")

    # compare the guess to the replaced word
    if guess == replace_word:
        print("That's right!")
    else:
        print("Incorrect, {} had been replaced.".format(replace_word))