![](/img/trans.png)
[英]Python: Search for string from dictionaryCSV file and display matching rows
[英]Python: Search for string on a text file and display matching rows
我現在有這個程序,它允許用戶從一個類別中進行選擇(從文件中提取)。 然后它將打印該文本文件中的大學或人。
我接下來要在我的代碼中做的是讓用戶從該文件中搜索特定字符串,它將顯示具有該匹配字符串的大學和人員。 它可以是該文件中的整個單詞或字符串的一部分。
我需要有關搜索給定字符串或字符串的一部分並顯示匹配類別(大學和人物)的幫助。
例子:
搜索: ohn
輸出:
大學:加州大學洛杉磯分校姓名:約翰凱利
大學:孟菲斯大學 姓名:Taylor J ohn son
這是我當前的文本文件:
"UniversityName","ContactName"
"UCLA","John Kelly"
"UofFlorida","Mary Elizabeth"
"U of Memphis","Taylor Johnson"
"Harvard","Robert Fax"
這是我到目前為止對我的代碼所做的:
def load_data(file_name):
university_data=[]
with open(file_name,'r') as rd_file:
for line in rd_file.readlines():
line=line.strip().split(',')
T = line[0],line[1]
university_data.append(T)
return university_data
def main():
filename='List.txt'
university_data = load_data(filename)
print('[1] University\n[2] Contact 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[0])
elif choice=='2':
for university in university_data:
print(university[1])
elif choice =='3':
print('Thank You')
break
elif choice =='4':
print("Search Section Here")
else:
print('Invalid selection')
main()
鑒於您的數據:
university_data = [["UniversityName","ContactName"],
["UCLA","John Kelly"],
["UofFlorida","Mary Elizabeth"],
["U of Memphis","Taylor Johnson"],
["Harvard","Robert Fax"]]
使用str.join
:
def search(key, data):
for l in data:
if key in ''.join(l):
print('University: %s Name: %s' % (l[0], l[1]))
search('ohn', university_data)
# University: UCLA Name: John Kelly
# University: U of Memphis Name: Taylor Johnson
與@Chris的先前回答類似,如果您想忽略搜索詞的大寫或小寫,可以在search
功能中添加lower()
。
def search(key, mydata):
for l in mydata:
if key in (''.join(l)).lower():
print('University: %s Name: %s' % (l[0], l[1]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.