如何从文本文件中打印一行的特定部分?

时间:2019-06-18 21:18:37

标签: python-3.x

我正在研究一个问答游戏,询问用户歌曲的标题,当歌曲显示为标题中每个单词的首字母以及旁边的歌手时。我有一个包含50首歌曲的文本文件,所有文件都带有数字(01、02等),标题中每个单词的首字母(例如“ Wonderwall”将显示为“ W_ _ _ _ _ _ _ _ _”) ”,实际的完整歌曲名称和歌手姓名,均用逗号分隔。尝试向用户显示问题时,出现错误

title = field[1]
IndexError: list index out of range

如何解决此问题?

我曾经设法使该程序完全正常运行,但是我对其进行了编辑,因此问题处于while循环中,现在不起作用了。

编辑-

我已经用ActualTitle字段完全填充了文本文件,但是它仍然返回错误,并且我还删除了一些代码问题,这是下面的文本文件示例:

01,O_ _ T_ _ _ R_ _ _,Old Town Road,Lil Nas X

02,B_ _ G_ _,Bad Guy,Billie Eilish

03,H_ _ _ W_ _ _ M_,Here With Me,Marshmello

04,A_ _ S_ _ _,All Star,Smash Mouth

05,T_ _ _,Talk,Khalid

06,E_ _ _ _ _ _ _ _,Earfquake,Tyler The Creator

07,S_ _ _ _ _,Sucker,Jonas Brothers

08,S_ _ _ _ _ _ _ _,Sunflower,Post Malone

09,P_ _ _ _ _ _,Perfect,Ed Sheeran

10,F_ _ _ _ _ L_ _ _ M_,Friend Like Me,Will Smith

我还更新了以下代码:

    # giving the score and lives variables
score = 0
lives = 2
# importing the songs for the questions
songs = open("songsAndArtists.txt","r")
# a while loop for if the answer is right
correctAns = True
while correctAns == True and lives != 0:
    # reading the specific lines and sections
    question = songs.readlines()
    for line in question:
        field = line.split(",")
        num = int(field[0])
        actualTitle = field[1]
        title = field[2]
        artist = field[3]
    print("Song no.",num,":")
    time.sleep(1)
    print("What is the full title of",actualTitle,"by",artist)
    guess = str(input())
    # give user 3 points for correct on first try
    if guess == (title):
        print("Correct! +3 points")
        time.sleep(0.5)
        print()
        score = score + 3
        print("You have",score,"points")
        print()
        False
    # give user a second chance to guess
    elif guess != (title):
        print("Your guess is wrong, try again")
        print()
        print("What is the full title of",actualTitle,"by",artist)
        guess2 = str(input())
        lives = lives - 1
        True
        # give user 1 point for correct on second try
        if guess2 == (title):
            print("You are right on your second try, +1 point!")
            score = score + 1
            time.sleep(0.5)
            print()
            print("You have",score,"points")
            print()
            False
        # user didnt answer question correct, game over   
        elif guess2 != (title):
            lives = lives - 1
            # writing user points to score file
            with open("scores.txt", "a") as score_board:
                print("You got that question wrong too many times, game over!")
                print("Your total score is",score)
                score_board.write("%d\n" % score)
                score_board.write("\n")
            if score >= 60:
                print("You did well!")
                exit()
            elif score >= 20 and score < 60:
                print("Not too bad, but you could have done better.")
                exit()
            elif score < 20 and score >= 0:
                print("That's not a very good score :(")
                exit()

songs.close()

我希望文本文件中名为“ actualTitle”的每一行的片段都与“ artist”片段一起输出给用户,但是相反,它出现了我之前提到的错误:

title = field[1]
IndexError: list index out of range

我觉得这有一个简单的解决方案,我有点迷失了,所以我们将不胜感激。 谢谢任何帮助的人:)

更新(再次) 我已经解决了IndexError的问题,不再显示它,但是现在程序仅从“歌曲”文本文件中输出最后一行,并重复执行此操作。另外,我已经更改了while循环的名称,并且大部分都在其中运行,并且为“ score”变量添加了文件写入系统(不用担心,它可以工作),但是我仍然遇到问题仅输出最后一行。

我现在包括一个词典部分,如下所示:

question = songs.readlines()
    for line in question:
        field = line.split(",")
        num = int(field[0])
        title = field[1]
        actualTitle = field[2]
        artist = field[3]
        # using dictionary for each field
        dictNum = {
            num: field[0]
        }
        dictTitle = {
            title: field[1]
        }
        dictActual = {
            actualTitle: field[2]
        }
        dictArtist = {
            artist: field[3]
        }

但是它不起作用,我很困惑 (注意:我已经做到了,所以问题的所有输出都是字典,例如'dictActual'等。

1 个答案:

答案 0 :(得分:0)

songs.readline()存在问题,它将仅读取下一行。因此,当您遍历该行时,它会遍历该行中的字符,并且当字符.split(',')不是','时,字符上的','始终会给出大小为1的列表,字符是question = songs.readline() 。因此,大多数情况下,list [1]都会给出索引超出范围的异常。

修复:

替换

question = songs.readlines()

使用

field = line.split(",")
num = int(field[0])
actualTitle = field[1]
title = field[2]
artist = field[3]

PS:

for循环结束后,所有信息都丢失了,但是最后一行:

{{1}}

您只需分配变量,并且在每次迭代中,它们都将被覆盖!执行循环后,变量中仅可见最后一行的数据。

您应将行数据保存在字典中,以便以后可以通过键查找(在您的情况下,field [0]可以是键)。