python - How to find specific word in a text file? -
i know how find specific word in text file without maybe using module re. current code:
searchfile = open("menu.txt", "r") mylist = [] cho = input("what cusine view menu for") line in searchfile: mylist.append(line+"\n") splitted_line = line.split(',') print(splitted_line[0]) indian = (mylist[0]) mexican = (mylist[1]) italian = (mylist[2]) if 'mexican' in cho: print(mexican) elif 'indian' in cho: print(indian) elif 'italian' in cho: print(italian) searchfile.close() cho2 = input("would order or wait till later") if cho2 == 'now': import practiseassessment.py if cho2 == 'later': print("ok more information contact hungry horse @ 07969214142") this text file:
lamb curry , indian , chicken curry , indian vegtable curry , indian tacos , mexican fajitas , mexican nachos , mexican margherita pizza , italian vegetable pizza , italian bbq chicken pizza , italian i want print indian food when cho == indian. want text file new line every dish
this 1 way approach problem. can see, can python's builtin strings.
note use str.lower().strip() normalize search terms , menu items before comparing them. give more generous results , not punish users inputting spaces, , thing.
# first parse input file , create menu list open("food.txt", "r") foodfile: menu_items = ' '.join(foodfile.readlines()).strip().split(',') menu_items = [item.strip() item in menu_items] # menu_items list ['lamb curry', 'indian', 'chicken curry' ... etc # made next part loop, can test several search terms. # instead of searching on user input, can split menu several lists # in real world cases not useful. approach # users can search "pizza" or "chicken" in addition "mexican", "italian" etc. while true: cho = input("what cusine view menu for? ").lower().strip() if not cho: break # break loop if user submits empty search string search_results = [food food in menu_items if cho in food.lower()] print('\nfound %d items on meny matching "%s"' % (len(search_results), cho)) print(', '.join(search_results)) print('\ngoodbye') example output:
what cusine view menu for? indian
found 3 items on meny matching "indian" indian, indian vegtable curry, indian tacos
what cusine view menu for? mexican
found 3 items on meny matching "mexican" mexican fajitas, mexican nachos, mexican margherita pizza
what cusine view menu for? pizza
found 3 items on meny matching "pizza" mexican margherita pizza, italian vegetable pizza, italian bbq chicken pizza
Comments
Post a Comment