Python 如何在文本文件中查找特定单词?

Python 如何在文本文件中查找特定单词?,python,python-3.x,Python,Python 3.x,我想知道如何在不使用模块re的情况下在文本文件中查找特定单词。 这是我当前的代码: searchfile = open("Menu.txt", "r") myList = [] cho = input("What cusine would you like to view the menu for") for line in searchfile: myList.append(line+"\n") splitted_line = line.split(',') print(spli

我想知道如何在不使用模块re的情况下在文本文件中查找特定单词。 这是我当前的代码:

searchfile = open("Menu.txt", "r")
myList = []
cho = input("What cusine would you like to view the menu for")


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 you like to order now or wait till later")
if cho2 == 'now':
    import practiseassessment.py

if cho2 == 'later':
    print("Ok for more information contact hungry horse at 07969214142")
这是文本文件:

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
我只想在cho==印度人时打印印度食物。
我希望文本文件成为每道菜的新行

首先,我深入查看了您的数据,我想您忘记了一些逗号。因此,我假设输入数据如下所示:

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
lamb curry
chicken curry
vegtable curry
有几种方法可以获得所需的输出。然而,我使用字符串和列表操作只是为了避免使用诸如re之类的附加Python模块。 我正在使用的唯一模块是sys模块,如果由于列表长度不均匀而导致合并fine和origin失败,那么它将中止执行以退出程序。但是,在编写专用函数时,您可以通过使用适当的return语句来摆脱这个sys.ext。因此,该解决方案能够在无需额外模块的情况下工作。我认为使用sys.exit可以演示这个想法

有关更多说明,请参见代码中的注释:

import sys

with open('data.txt', newline='') as f:
    data = f.readlines()

stripped_data = [line.replace(' , ', ',') for line in data]

# print in order to double check
print(stripped_data)

# write the whole data into a single string without newlines
s = ''
for line in data:
     s += line.replace(' , ', ',').replace('\n', ',')

# split string into several parts (which will be the meals and the origin)        
sliced = [e for e in s.split(',') if e]

# print in order to double check
print(sliced)

# exit routine if list has uneven length since we would fail when trying to combine the pairs
if len(sliced) % 2:
    sys.exit('Uneven list length. Would fail to combine pairs.')

# generate a list containing tuples of meal and origin --> (meal, origin)    
pairs = [(sliced[i], sliced[i+1]) for i in range(0, len(sliced), 2)]  

# ask the user what he wants to get served
wanted = input('What do you want to have? ')

# generate the output based on the user's input by accessing the tuples
output = [i for i,k in pairs if k == wanted]

# print the output
print(output)

with open('output.txt', 'w') as f:
    for meal in output:
        f.write('{}\n'.format(meal))
如果用户需要,输出文件如下所示:

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
lamb curry
chicken curry
vegtable curry

这是解决问题的一种方法。正如您所看到的,您可以使用python的内置字符串做任何事情

请注意,在比较搜索词和菜单项之前,请使用str.lower.strip规范化它们。这将提供更慷慨的结果,而不是惩罚用户输入额外的空间,这通常是一件好事

# First parse you input file and create the menu list
with open("food.txt", "r") as foodfile:
    menu_items = ' '.join(foodfile.readlines()).strip().split(',')
menu_items = [item.strip() for item in menu_items]

# menu_items is now the list ['lamb curry', 'indian', 'chicken curry' ... etc

# I made the next part into a loop, so you can test several search terms.
# instead of searching on user input, you can split the menu into several lists
# but in most real world cases that is not really useful. With this approach
# users can search for "pizza" or "chicken" in addition to "mexican", "italian" etc. 

while True:
    cho = input("What cusine would you like to view the menu for? ").lower().strip()
    if not cho:  
        break  # break the loop if user submits an empty search string
    search_results = [food for food in menu_items if cho in food.lower()]
    print('\nFound %d items on the meny matching "%s"' % (len(search_results), cho))
    print(', '.join(search_results))

print('\ngoodbye') 
示例输出:

您想查看菜单中的哪一项内容?印第安人

在菜单上找到3个匹配的印度菜,印度菜 咖喱、印度玉米卷

您想查看菜单中的哪一项内容?墨西哥人

在菜单上找到了3个匹配的墨西哥fajitas,墨西哥 墨西哥玉米片,墨西哥玛格丽特披萨

您想查看菜单中的哪一项内容?披萨

在菜单上找到了3种与墨西哥玛格丽塔披萨相匹配的披萨, 意大利蔬菜披萨,意大利烤鸡披萨


您是否需要自己编写代码,或者您是否可以使用csv模块,甚至熊猫?@albert自己编写代码,因此不允许使用csv?将数据作为csv格式的数据进行处理将使事情变得相当简单。我只是对您的数据进行了更深入的研究。我想少了三个逗号。你能再检查一下你的数据片段吗?你从哪里获得数据?你忘记在分割后去掉空白。不要使用re,这是一个过度的技巧,但用户应该能够键入这样的句子我想要意大利语,我可以买一些意大利语,所以它应该在输入@Haken liden中查找关键字。你在原始问题中没有提到这一点。发布一个新问题。我对自然语言处理几乎没有经验,这正是像这样解析输入所需要的。这是先进的东西。