【问题标题】:how do I make an input equal to a line from another file如何使输入等于另一个文件中的一行
【发布时间】:2020-07-28 21:57:37
【问题描述】:

我必须创建一个游戏,在 python 中给出艺术家和歌曲标题每个单词的首字母。歌曲必须从外部文件中随机选择,用户必须猜测歌曲。

我制作了一个包含所有名称的文本文件,并使用readlines() 函数从文本文件中获取歌曲。

我遇到的问题是输入不等于文件的行,即使它完全相同。

代码如下:

random_number = random.randint(0,10)
name_of_songs = open("Names of songs.txt", "r")
song = str(name_of_songs.readlines()[random_number])
name_of_songs.close()
answer = input("what is the name of the song: ")
if answer == song:
    print("well done you got 3 points")

【问题讨论】:

    标签: python


    【解决方案1】:

    你的代码问题出在这里:

    str(name_of_songs.readlines()[random_number])
    

    readlines() 方法将返回文件中的行列表,在除最后一行之外的所有行的末尾都有一个尾随 '\n'。例如文件:

    Apple
    Banana
    Cherry
    

    将返回如下:

    ['Apple\n', 'Banana\n', 'Cherry']
    

    所以如果用户输入'Apple',结果是'Apple'不等于'Apple\n'

    您可以使用.read().splitlines() 解决此问题,这将返回一个没有'\n's 的列表。

    另外,使用open() 然后close() 是一种不好的做法。相反,请使用 with 声明:

    random_number = random.randint(0,10)
    
    with open("Names of songs.txt", "r") as name_of_songs:
        song = name_of_songs.read()splitlines()[random_number] # Note that since read returns strings, there is no need to convert it to a string again
    
    answer = input("What is the name of the song: ")
    if answer == song:
        print("well done you got 3 points")
    

    【讨论】:

      【解决方案2】:

      这样的代码:

      import csv
      name_of_songs = open("Names of songs.txt", "r")
      reader=csv.reader(name_of_songs)
      for eachRow in reader:
          //you will get each line here (eachRow)
      

      【讨论】:

        猜你喜欢
        • 2019-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多