python-当用户请求输入时从文件打印

时间:2017-08-02 18:49:42

标签: python

我已成功导入文本文件并将其存储在字典中。我希望能够要求用户输入他想要的号码并打印与用户想要的号码对应的值。例如,该文件包含2个名称1:chris 2:sam ...我希望程序向用户询问输入,并且用户输入2它应该从字典中打印sam。

这是我的代码:

file = open("songranks.txt","r")
d={}

#Repeat for each song in the text file
for line in file:

  #Let's split the line into an array called "fields" using the "," as a separator:
  fields = line.split(",")

  #and let's extract the data:
  songrank = fields[0]
  list =[fields[1],fields[2]]
  k = [str(x) for x in list]
  ["".join(k)]
  chris=len(k)-1
  k=k[0:chris]
  d[songrank]=k


#It is good practice to close the file at the end to free up resources
file.close()

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

在python中获取输入:

question = input('ask your question')

然后播放存储为字符串的答案。 所以你要说的是:

print(d[int(question)])

答案 1 :(得分:0)

您必须使用input()功能来获取用户输入,并且我建议您进行一些更改,以使您的程序更加紧凑和清晰。
我们应该避免使用与listinputandor等保留关键字匹配的变量名称,这就是您应该更改变量list的原因别的名字。

file = open("songranks.txt","r")
d={}

#Repeat for each song in the text file
for line in file:

  #Let's split the line into an array called "fields" using the "," as a separator:
  fields = line.split(",")

  #and let's extract the data:
  songrank = fields[0]
  li =[fields[1],fields[2]]
  k = ["".join(str(x)) for x in li][0]
  d[songrank]=k


#It is good practice to close the file at the end to free up resources
file.close()
# yes indeed it is good practice

get_track_id = input("Enter track id") # Ask for input
print(d[get_track_id]) # print the track name