gpt4 book ai didi

python - 如何从多个单词中获取第一个字母和 * 其余字母?

转载 作者:行者123 更新时间:2023-12-01 01:31:46 26 4
gpt4 key购买 nike

尝试创建一个猜谜游戏。

我有一个包含 2 列的 CSV 文件。第一个包含艺术家姓名,第二个包含歌曲标题

我希望能够显示随机艺术家姓名,然后显示歌曲标题中每个单词的第一个字母,例如

齐柏林飞艇 - S******** t* H*****

到目前为止,我已经能够让它从文件中随机选择一位艺术家并显示艺术家和歌曲标题

import random
import time

filesize = 11251
offset = random.randrange(filesize)
words = []
print("Welcome to the music guessing game")
def randomsong():
file = open("musicFile.csv","r")
file.seek(offset)
file.readline()
line =file.readline()
data = line.split(",")
print (data[0], data[1])
song = data[1]
song = str(song)
print(song)
guesses = 2
Score = 0
song = song.lower()

while guesses != 0:
yourguess = input ("Guess the name of the song")
if yourguess == song:
print ("Well Done!")
else:
print ("Incorrect, try again ")
guesses = guesses -1
print("Game Over!!!")

randomsong()

然后用户应该能够尝试猜测这首歌。

我知道上面的代码正在打印艺术家和歌曲标题,然后再次打印歌曲标题,我只是对其进行测试以确保它选择了我想要的内容。

单独的问题:即使我输入了正确的答案,IF 语句总是说“不正确,请重试”。

我不只是在寻找能为我做这件事的人;如果您能解释我哪里出错了,我将不胜感激。

最佳答案

遇到此类问题时,请先从最小的部分开始,从内到外进行处理。

如何获取单个单词并显示第一个字母,其余字母带有星号?

>>> word = 'Hello'
# Use indexing to get the first letter at position 0
>>> word[0]
'H'
# Use indexing to get the remaining letters from position 1 onwards
>>> word[1:]
'ello'
# Use len to get the length of the remaining letters
>>> len(word[1:])
4
# Use the result to multiply a string containing a single asterisk
>>> '*' * len(word[1:])
'****'
# put it together
>>> word[0] + '*' * len(word[1:])
'H****'

现在您知道可以使用 word[0] + '*' * len(word[1:]) 获得单个单词的结果,将其转换为函数:

def hide_word(word):
return word[0] + '*' * len(word[1:])

现在,如果您有一串包含多个单词的字符串,则可以使用 .split() 将其转换为单个单词的列表。您面临的挑战:如何将结果重新组合成新的标题字符串?

关于python - 如何从多个单词中获取第一个字母和 * 其余字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52792004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com