2017-08-02 85 views
0

我已经成功地导入了文本文件并将其存储在dictionary.i希望能够要求用户输入他想要的数字并打印值与用户想要的数字相对应。例如该文件包含2个名字1:chris 2:sam ...我想让程序询问用户输入,用户输入2,它应该打印字典中的sam。python-当用户要求输入时从文件打印

这里是我的代码:

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() 

任何帮助,将不胜感激。

+0

这行是什么?[“”.join(k)]'在干什么? –

+0

我没有复制代码和yea [“”.join(k)]应该加入列表= [字段[1],字段[2]]中的字符串] –

+0

但你没有分配任何地方。对不起,我没有试图在无论如何粗鲁。检查我的答案是否有帮助。 –

回答

0

要获得输入蟒蛇:

question = input('ask your question') 

然后保存为一个字符串的答案发挥。 所以从你说的话是这样的:

print(d[int(question)]) 
0

你必须使用input()函数来获取用户输入和一些变化下面我建议让你的程序更加紧凑和清晰。
我们应该避免使用与保留关键字匹配的变量名称,例如list,input,and,or等,这就是为什么您应该将变量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