【发布时间】:2019-08-04 13:24:33
【问题描述】:
我现在有这个程序,它允许用户从一个类别中进行选择(从文件中提取)。然后它将使用字典打印大学数据。
接下来我想对我的代码做的是让用户从该文件中搜索特定的字符串,它会显示所有的键。它可以是该文件中的整个单词或字符串的一部分。
我在搜索给定字符串或字符串的一部分以及显示匹配类别(NameID、StudentName、University、Phone、State)方面需要帮助。
示例:
搜索:开启
输出:(注意:这是字典格式)
{'NameID': 'JSNOW', ' StudentName': ' Jon Snow', ' University': ' UofWinterfell', ' Phone': ' 324234423', ' State': 'Westeros'}
{'NameID': 'JJONS', ' StudentName': ' Joe Jonson', ' University': ' NYU', ' Phone': ' 123432333', ' State': 'New York'}
我的文本文件如下所示:
NameID, StudentName, University, Phone, State
JJONS, Joe Jonson, NYU, 123432333, New York
SROGE, Steve Rogers, UofI, 324324423, New York
JSNOW, Jon Snow, UofWinterfell, 324234423, Westeros
DTARG, Daenerys Targaryen, Dragonstone, 345345, NULL
这是我目前所拥有的:
import csv
def load_data(file_name):
university_data=[]
with open("file.csv", mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file, skipinitialspace=True)
for col in csv_reader:
university_data.append(dict(col))
print(university_data)
return university_data
# def search_file():
# for l in data:
# no idea what to do here
def main():
filename='file.csv'
university_data = load_data(filename)
print('[1] University\n[2] Student Name\n[3] Exit\n[4] Search')
while True:
choice=input('Enter choice 1/2/3? ')
if choice=='1':
for university in university_data:
print(university['University'])
elif choice=='2':
for university in university_data:
print(university['StudentName'])
elif choice =='3':
print('Thank You')
break
elif choice =='4':
search_file()
else:
print('Invalid selection')
main()
我需要选择 4 才能工作。我会忽略选项 1 和 2,因为它们只显示名称而不是字典格式。
【问题讨论】:
标签: python python-3.x string dictionary search