2016-05-19 27 views
0

搜索关键词的文本文件我有鸡肉的文本文件,食谱鸡作为1号线和牛肉,牛肉配方为2行使用.split蟒蛇

我可以搜索牛肉或鸡肉配方如果用户只输入牛肉或鸡肉。但我想搜索牛肉食谱,如果用户键入“我想搜索牛肉食谱”或鸡....

我想使用.split,但不是那里。以下是我的代码。

while True: 
    food = input ("What food? ") 
    file = open("meals.txt", "r") 
     line = file.readline() 
     data = line.split(",") 
     if data[0] == food: 
      print(data[1]) 
    file.close() 
+0

如果你知道第一个单词是关键字,你可以做一些类似'if关键字食物:'来检查关键字是否在输入短语中的任何地方。 –

+0

问题如何搜索文本,或者如何让关键字不受问题? –

+0

使用这段代码http://stackoverflow.com/questions/6531482/how-to-check-if-a-string-contains-an-element-from-a-list-in-python/6531704#6531704搜索如果输入词组有任何单词是存在于list1 = ['鸡','牛肉'] –

回答

0

您将希望将“食物”项目放入列表中,并对其进行迭代。

food_type = food.split() 
for type in food_type: 
    if type == 'beef': 
     #do something 
    elif type == 'chicken': 
     #do something else 
0

理想情况下,您应该使用elasticsearch进行此操作。但是,如果你想做字符串解析。

while True: 
food = input ("What food? ") 
food_tokens = food.split() 
file = open("meals.txt", "r") 
    line = file.readline() 
    data = line.split(",") 
    for food_token in food_tokens: 
     if data[0] == food_token: 
      print(data[1]) 
file.close() 

这将检查单词“牛肉”和“鸡肉”,如果输入包含它们,那么它会打印您想要的数据。

0

首先,您需要某种有效搜索词的列表,在这种情况下keywords = ['beef', 'chicken']。否则,如果有人要搜索“鸡肉食谱”,那么您可能会在“美味的牛肉食谱”中找到“食谱”。然后你会发现在用户输入的所有有效关键字,然后匹配有效问卷的饭菜:

keywords = ['beef', 'chicken'] 
userinput = input("what food? ") 

# generate a list of meals 
with open("meals.txt", "r") as file: 
    meals = file.readlines() 

for word in userinput.split(): 
    if word in keywords: 
    for meal in meals: 
     if word in meal: 
     # yay found one, store it or something 
0

您可以使用正则表达式:

import re 

foodType = re.search('(beef|chicken)', food) 
if foodType is None: 
    print 'beef or chicken, make your choice.' 
else: 
    print foodType.group(1) 
    """whatever you meant to do with beef or chicken instead. 
     foodType.group(1) is 'chicken' or 'beef' 
    """ 

在那里,如果食物类型为无,这意味着您的用户根本没有输入鸡肉或牛肉。否则,将foodType.group(1)设置为鸡肉或牛肉,无论输入的是哪一个。我只是打印一张照片,但是从那里你可以随心所欲地做任何事情。

0
file = open("txt", "r") 
all_lines = file.readlines() 

while True: 
    food = raw_input ("What food? ") 
    for line in all_lines: 
     data = line.split(',') 
     if data[0] == food: 
      print "Found %s" % food 
      print "data[1] is %s" % data[1] 
      break 
    else: 
     print "Not found %s" % food