2017-10-21 160 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