我有一个文本文件供给我的数组。我用csv导入了它们。我有多个数组,存储数据,如人名,地址,电子邮件等。我试图根据用户输入打印出单个数组的值。
elif option==3:
print("Which report would you like to run?")
time.sleep(1)
reportmenu()
while True:
choice=int(input(" "))
if choice ==1:
city_input=raw_input("Please enter a city which you would like to display all students from")
for row in City:
if city_input in City:
cityindex=City.index(city_input)
print("{} {} {} {} {} {} {}".format(ID[cityindex],Surname[cityindex],FirstName[cityindex],City[cityindex],Phone_Number[cityindex],Gender[cityindex],Email[cityindex]))
因此,如果用户输入城市的名称,并且它出现在City数组中,则程序可以打印出与存储在其他阵列中的用户相关的其他相关信息。我已经尝试了基于用户输入的索引,但这不起作用,我得到以下输出:
001,Surname1,Shaun,18/09/86,Sheffield,012345,Male,shaun@shaun.com
001,Surname1,Shaun,18/09/86,Sheffield,012345,Male,shaun@shaun.com
001,Surname1,Shaun,18/09/86,Sheffield,012345,Male,shaun@shaun.com
001,Surname1,Shaun,18/09/86,Sheffield,012345,Male,shaun@shaun.com
在我的文本文件中(转换为csv)我有以下数据(到目前为止):
001,Surname1,Shaun,18/09/86,Sheffield,012345,Male,shaun@shaun.com
002,Surname2,Ifty,01/01/01,Rotherham,0123456,Male,Ifty@ifty.com
003,Surname3,Dawn,01/01/01,Doncaster,0123456,Female,Dawn@Dawn.com
004,Surname4,Bryan,01/01/01,Sheffield,012345,Male,Bryan@deaf.com
因此,如果用户输入'谢菲尔德',它应该显示肖恩和布莱恩的信息。
任何帮助将不胜感激。
答案 0 :(得分:0)
如果数据库在csv文件中,我喜欢使用像这样的pandas:
import pandas as pd
df = pd.read_csv('citydat.csv', header=None,
names=['code','sur','name','date','city','post','sex','email'])
df.set_index('code', inplace=True, drop=True)
cities = df.city.unique()
while True:
city = input('enter city: ').title()
if city in cities:
print(df[df.city==city])
elif city == '':
break
else:
print(city,'not in database')
运行它看起来像这样:
enter city: new york
New York not in database
enter city: sheffield
sur name date city post sex email
code
1 Surname1 Shaun 18/09/86 Sheffield 12345 Male shaun@shaun.com
4 Surname4 Bryan 01/01/01 Sheffield 12345 Male Bryan@deaf.com
enter city:
编辑:如果你没有熊猫,你可以使用csv模块做这样的事情,这应该在你的python发行版中。
import csv
with open('citydat.csv') as csvfile:
reader = list(csv.reader(csvfile))
while True:
city = input('enter city: ').title()
if city == '':
break
lines = [line for line in reader if line[4]==city] # city name is index 4
if lines == []:
print(city,'not in database')
else:
for line in lines:
print(line)
enter city: new york
New York not in database
enter city: sheffield
['001', 'Surname1', 'Shaun', '18/09/86', 'Sheffield', '012345', 'Male', 'shaun@shaun.com']
['004', 'Surname4', 'Bryan', '01/01/01', 'Sheffield', '012345', 'Male', 'Bryan@deaf.com']
enter city: boston
Boston not in database
enter city:
如果您没有csv模块,或者由于某种原因不想使用它(?)那么您可以使用相同的逻辑但是将文件作为文本打开并进行进一步处理线条。