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

时间:2016-02-06 15:18:42

标签: 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(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 == indian时打印印度食物。 我希望文本文件成为每道菜的新行

2 个答案:

答案 0 :(得分:-1)

首先,我深入了解了您的数据,我认为您忘记了一些逗号。所以我假设输入数据如下所示:

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

有多种方法可以获得所需的输出。但是,我仅使用stringlist操作,以避免使用其他Python模块,如re。 我正在使用的唯一模块是sys模块,如果由于列表长度不均匀而导致进餐和原点组合失败,则中止执行以退出程序。但是,在使用适当的sys.ext()语句编写专用函数时,可以删除此return。因此,该解决方案无需额外模块即可工作。我认为使用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))

如果用户想要indian餐,则输出文件如下所示:

lamb curry
chicken curry
vegtable curry

答案 1 :(得分:-1)

这是解决问题的一种方法。如您所见,您可以使用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') 

示例输出:

  

您希望查看菜单的cusine是什么?的

     

在meny匹配"印度"找到3项印度,印度蔬菜   咖喱,印度炸玉米饼

     

您希望查看菜单的cusine是什么?的

     

在墨西哥"墨西哥"找到了3个项目。墨西哥法加它,墨西哥   墨西哥玉米片,墨西哥玛格丽塔披萨

     

您希望查看菜单的cusine是什么?的比萨饼

     

在meny匹配"披萨"上找到3个项目墨西哥玛格丽塔披萨,   意大利蔬菜披萨,意大利烧烤鸡肉披萨