Python.split()在我的程序中不起作用

2024-03-29 01:56:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个音乐猜谜游戏,在这个游戏中,艺术家的全名和标题的每个单词的第一个字母都会给出。我当前的代码(有效)能够处理一个单词给艺术家,一个单词用于歌曲;例如伊甸夜曲。在

然而,如果艺术家的名字中有两个部分(EdSheeran),我的代码就不能处理这个问题(类似于歌曲名)。 因此,我想使用限定符来分割艺术家和歌曲,这样我就可以打印出艺术家的全名,然后使用try:except:函数来打印歌曲每个单词的第一个字母(如果有)。在

当我只使用空格时.split()函数可以正常工作,但是当我使用单词或符号('DOT','|')时,它就不再工作了。在

这是有效的代码:

with open('MusicNames.txt') as file:
    text = file.readlines()[number]
    artist = text.split()[0]
    print('Artist: ' + artist)
    song = text.split()[1]
    songLetter = text.split()[1][0]
    print('First letter: ' + songLetter)

上面的代码适用于这种风格的艺术家和歌曲:

The code above works for this style of Artist and Song

但是,它在这种情况下不起作用:

However, it will not work in this instance

因此,我使用限定词:

^{pr2}$

明智点,它似乎有用。但是,它不再认为答案是正确的,因此请我再猜一次:

Look wise, it appears to work. However, it no longer thinks the answer is correct and therefore asks me to guess again.

我很困惑为什么会发生这种情况,因为如果我要打印两个变量,它们必须相等才能正确,它们会完全相同。虽然程序不这么认为。在

for i in range(2):
        guess = input('\nGuess: ')
        if guess == song and triesLeft == 2:
            global score
            score += 3
            print('Correct! Current Score: ' + str(score))

在else语句中,我把:print(guess)print(song):

In the else statement further on I put: print(guess) print(song)

感谢您阅读所有这些,并感谢任何帮助!在


Tags: 函数代码text游戏songartist字母歌曲
1条回答
网友
1楼 · 发布于 2024-03-29 01:56:43

你的短信阅读看起来很可疑:

text = file.readlines()[number]

Doku - hidden in IOBase

它的工作原理与readline()相似,因为它:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

(来自Dok

您永远不会从标题中删去'\n',因此它本质上是而不是euqal到您的输入,因为这个结尾没有'\n'。在

您可以使用song = song.rstrip()link)从中删除包括换行符在内的空白。在

对于多词歌曲标题,您可能需要检查str.split([sep[, maxsplit]])dokumentationhere,并按如下方式使用:

^{pr2}$

相关问题 更多 >