python - 我坚持执行有关列表和附加整数和字符串的特定任务

标签 python string

我已经设置了 5 个任务来完成其中 4 个我已经完成但是第 5 个是一个斗争这些是任务:

  1. 创建一个文本文件并在其中写下 10 个英语单词的列表。
  2. 开发程序的一部分,从这个文本文件中读取单词并随机选择一个。
  3. 开发程序的一部分,将单词中的每个字母替换为字母表中的相应数字。例如 CAT 将变为 3、1、20。
  4. 开发允许用户输入数字然后输入他们认为代表的字母的程序部分。该程序应该告诉他们它是对还是错,然后显示带有正确替换的单词。例如,如果用户输入 A 代表 1,那么它应该说"is"或类似的,然后显示 3、A、20。
  5. 开发程序的一部分,继续这个过程,直到用户猜对了整个单词。

我已经完成了最多 4 个,但第 5 个我正在为我的代码苦苦挣扎:

#Import Section
import random
import csv
import math

#Start Variables
Random_Words = []
alph = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',     'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
word_2 = []

#Foundation Code (List of words)
words = open('List_Words.txt') 
first_10 = []
for line in words:
    Random_Words.append(line[:-1])

#Making the random word 
word = random.choice(Random_Words)
word = list(word)

#Making the random word into an alphabetical numeral
for character in word:
    i = 0 
    while i < 26:
        if character == alph[i]:
            word_2.append(num[i])
        i = i + 1

#print word
#print Random_word
print word_2    

#Letting the person guess the word/ letter   
guess_number = int(raw_input("choose a number:  "))
guess_letter = raw_input("choose a letter:  ")

i = word.index(guess_letter)
if word_2[i] == guess_number:
    print "Correct"

else:
    print "Nope"

最佳答案

while(1): 
    print word_2  
    #Letting the person guess the word/ letter   
    guess_number = int(raw_input("choose a number:  "))
    guess_letter = raw_input("choose a letter:  ")

    i = word.index(guess_letter)
    if word_2[i] == guess_number:
        word_2[i] = guess_letter # put guessed letter into word_2, for example "3 A 20"
        print "Correct: ", word_2
        if word == word_2:
            break
    else:
        print "Nope"
    print "continue guessing"

关于python - 我坚持执行有关列表和附加整数和字符串的特定任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21657375/

相关文章:

python - 使用 dictConfig 的 Python 日志记录问题

python - 套接字输出被截断到下一个文件

c# - 字符串实习?

C 中的连接 char* 无法解决段错误

javascript - 将字符串中的各个字母设置为不同的颜色

string - 在T-SQL中获取字符串的特定部分

xcode - 当尝试包含 "in a String, using\"时有效但\也包含在内

python - 如何将 keras 模型转换为 Protocol Buffer (.pb) 文件?

python - 根据单元格值重命名数据框列

python - 如何将 JSON 时间序列与具有相同列名的 pandas 一起使用