2017-08-17 98 views
-1

我正在製作一個程序,要求用戶輸入他們的學生ID,並顯示學生信息,如學生ID和學生姓名。我首先要求用戶輸入他們的ID,然後讀取一個.txt文件,並檢查學生ID是否匹配,然後打印出用戶的特定學生的.txt文件信息的內容。在尋找。將用戶輸入與Python中的文件記錄匹配

這是我的文件

201707001 Michael_Tan 
201707002 Richard_Lee_Wai_Yong 
201707003 Jean_Yip 
201707004 Mark_Lee 
201707005 Linda_Wong 
201707006 Karen_Tan 
201707007 James_Bond 
201707008 Sandra_Smith 
201707009 Paul_Garcia 
201707010 Donald_Lim 

的內容,這是我的源代碼

# user can find out the student info 
userInput = input("Please enter a student ID: ") 

# read the students file 
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f: 
    studentFile = f.readlines() 
    for student in studentFile: 
     stdId, stdName = student.strip().split(" ",1) 


# check if the student exist 
matched = True 

while matched: 
    if userInput == stdId: 
     print("True") 
    else: 
     print("False") 
     matched = False 
     break 

但輸出我得到的是虛假的,即使我鍵入的確切studentID

+1

看到作爲這道題的學生信息,我認爲你是一個,這就是功課。如果情況並非如此,請不好意思。但如果是這樣的話,請在提問有關SO之前去找你的教授。 – ktb

回答

0

你應該在閱讀文件時執行檢查。否則,您正在拆分並獲取您的信息,但這些數據在隨後的迭代中丟失。試試這個:

with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f: 
    studentFile = f.readlines() 
    for student in studentFile: 
     stdId, stdName = student.strip().split() 
     if userInput == stdId: 
      print(stdName) 
      break 

更妙的是,對於大文件,迭代行明智的。請勿使用f.readlines,因爲它會將所有數據加載到內存中。

with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f: 
    for line in f: 
     stdId, stdName = line.strip().split() 
     if userInput == stdId: 
      print(stdName) 
      break 
0

既然這樣你的代碼遍歷每個ID和姓名以及各分配到stdIdstdName,但你在這之前退出循環檢查匹配...因爲它只保存存儲的最後的值在循環中的那些變量中。你需要在循環檢查,因爲這樣

# user can find out the student info 
userInput = input("Please enter a student ID: ") 

# read the students file 
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f: 
    studentFile = f.readlines() 
    for student in studentFile: 
     stdId, stdName = student.strip().split(" ",1) 
     # check for a match here, break the loop if a match is found 
-1

使用raw_input而不是input

你幾乎從不想使用input,因爲它確實評估。在這種情況下,輸入一個精確的整數會給你一個整數,而文件給你一個字符串,所以它不會匹配。

您在代碼中有其他小問題。

  • 如果循環與userInput == stdId一起輸入,您將永遠循環打印True
  • 你從來沒有真正搜索通過學生的ID,你查一下你以前的循環
    • 最後一組(對於這一點,如果你打算做多個用戶的查詢,或只是看看,我會建議使用字典你讀文件的一個簡單的腳本線)
+0

downvote的任何原因?我應該注意到我回答了通用版本,而不是做這項工作,因爲這一行表明它是一個確切的家庭作業(而不是一般性問題):'C:\\ Users \\ jaspe \\ Desktop \\ PADS Assignment \\ Student.txt' – Cireo

相關問題