回归价值

时间:2017-10-27 10:36:41

标签: python function

def extract_info(text, price):
   company_name = ['BMW','AUDI','MERCEDES','TOYOTA']
   car_type = ['Saloon', 'Hatchback','Sedan']
   if any(word in text for word in company_name):
      for word in company_name:
         matchWord = text.split()
         if word in matchWord:
            return (word)
   elif any(word in text for word in car_type):
      for word in car_type:
        matchWord = text.split()
        if word in matchWord:
            return (word)

   else:
      productType = re.search('car', text)
      if productType is not None:
        productvalue = productType.group(0)
        return (productvalue)

  numDoor = re.search('[0-9]-door',text)
  if numDoor is not None:
        matchDoor = numDoor.group(0)
        return (matchDoor)
  else:
    return ('No match')

我试图返回一个值但是,无法获得所有的值。虽然我在打印时输出了输出。

我正在使用一根字符串“低维护,5门安全车”

如果字符串获得任何单词或与正则表达式匹配,则提取代码。

2 个答案:

答案 0 :(得分:0)

您可以使用return

替换print语句
if numDoor is not None:
    matchDoor = numDoor.group(0)
    return matchDoor
else:
    return 'No match'

答案 1 :(得分:0)

因为一个函数只能返回一次。所以在第18行之后:

    return productType

它返回函数的最终返回值,它将永远不会在第18行之后执行。第19行之后的代码没有执行那就是为什么你没有得到其余的结果。如果你想返回一堆输出,那么只需在列表中追加或使用dict保存不同的结果,然后最后返回该变量并根据需要使用该变量数据。

一个例子:

import re
def extract_info(text, price):
    final_output={}
    company_name = ['BMW','AUDI','MERCEDES','TOYOTA']
    car_type = ['Saloon', 'Hatchback','Sedan']
    if any(word in text for word in company_name):
        for word in company_name:
            matchWord = text.split()
            if word in matchWord:
                final_output['word']=word
    elif any(word in text for word in car_type):
        for word in car_type:
            matchWord = text.split()
            if word in matchWord:
                final_output['word']=word
    else:
        productType = re.search('car', text)
        if productType is not None:
            final_output['product_type']=productType.group(0)
    numDoor = re.search('[0-9]-door', text)
    if numDoor is not None:
        matchDoor = numDoor.group(0)
        final_output['matchdoor']=matchDoor
    else:
        final_output['matchdoor']='None'

    return final_output

print(extract_info("A low maintenance, 5-door car that's safe",23))