2017-08-02 82 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