2017-10-21 159 views
0

我有一個文本文件,載列於本佈局:遍歷一個文本文件,輸入

Greg,Computer Science,Hard,5

Alex,Computer Science,Medium,2

Fiona,Maths,Easy,0

Cassie,Maths,Medium,5

Alex,Maths,Medium,1

在我的節目,我希望用戶能夠選擇一個特定的名字,看看他們的結果。我給這家代碼如下所示:

name = input("Enter name: ") 
for each in file: 
    each = each.split(",") 
    realName = each[0] 
    subject = each[1] 
    difficulty = each[2] 
    score = each[3] 
    if name == realName: 
     print(subject, difficulty, score) 
     break 
else: 
    print() 
    print("Invalid name.") 
    name = input("Re-enter your name: ") 

有幾件事情是錯的,雖然我想不出該怎麼做:

  1. 如果用戶輸入「亞歷克斯」,只有一個他的結果將被顯示。
  2. 如果輸入了錯誤的名字一次,輸入的其他名稱將返回爲「無效」。
  3. 如果輸入正確的名稱並顯示結果,程序將繼續詢問名稱。

有沒有人有任何解決這些問題的方法?

回答

0

如果您要反覆查詢您的文件,建議您先將數據預加載到字典中,然後在需要時打印數據。就像這樣:

data = {} 
with open('file.txt', 'r') as file: 
    for line in file: 
     realName, subject, difficulty, score = each.split(',') 
     data.setdefault(realName, []).append((subject, difficulty, score)) 

while True: 
    name = input('>>> ') 
    data.get(name, 'Invalid Name') 

這解決了問題一和二。如果你只是想打破後的第一個有效的名稱輸入,可以查詢的dict.get返回值:

while True: 
    name = input('>>> ') 
    result = data.get(name) 
    if result: 
     print(result) 
     break 

    print('Invalid name') 

這解決了問題,有三種。

+0

我對python很陌生,所以我不確定第5行的意思。當我將其複製到我的程序並運行它時,它給了'AttributeError:'列表'對象沒有屬性'setdefault''。 –

+0

@ GregD'Silva啊,呃。它應該是'{}',而不是'[]'。請參閱編輯。 –

+0

@ GregD'Silva如果您的問題得到解答,請[接受答案](https://stackoverflow.com/help/someone-answers)。謝謝。 –

0

你最好使用csv module,因爲你的文件語法是簡單的CSV。

然後,您可以遍歷行(每行將是一個值的數組)。

import csv 

def parse_csv_file(csv_file, operation, value, index): 
    with open(csv_file, newline='') as file: 
     reader = csv.reader(file, delimiter=',', 
          quotechar='|') 
     return operation(reader, 
         value, index) 


def find_first_row(csv_reader, value, index): 
    for row in csv_reader: 
     if row[index] == value: 
      return row 
    return None 


def main(): 

    query = input('Enter a name: ') 

    result = parse_csv_file('file.csv', 
          find_first_row, 
          query, 0) 

    if result: 
     print(result) 
    else: 
     print('Nothing found!') 

main() 
+0

切換到CSV來解析OP的文件並不能解決他們眼前的問題。 –

+0

添加了示例代碼,顯示如何解析CSV。 – gchiconi