【问题标题】:Prevent AttributeError: 'NoneType' has no attribute 'group' in one-line regex function防止 AttributeError:“NoneType”在单行正则表达式函数中没有属性“组”
【发布时间】:2015-11-18 11:23:31
【问题描述】:

在下面的函数中,f1 使用re.findall 并且可以将与dictionary 中的键不匹配的正则表达式选择传递为else ""

但是,f2re.search.group 一起使用,并且不能传递与dictionary 中的键不匹配的正则表达式选择。报错:

AttributeError: 'NoneType' 对象没有属性 'group'

dictionary = {"vanilla":"white", "strawberry":"red"}

string = "Yummy chocolate ice cream."

regex = re.compile(r"\b((%s)\S*)\b" %"|".join(dictionary.keys()), re.I)

def f(fruit):

    f1 = lambda x: dictionary[regex.findall(x)[0]] if regex.findall(x)[0] in dictionary else ""
    f2 = lambda x: dictionary[regex.search(x).group(2)] if regex.search(x).group(2) in dictionary else ""

    color_1 = f1(fruit)
    color_2 = f2(fruit)

    statement = "Buy " + color_2 + " ice cream in the grocery store."
    return statement

如何使f2 将不匹配项作为"" 传递而不会出现上述错误,最好使用尽可能少的代码行?请注意,我们必须使用re.search 并且可能使用.group,因此我们无法更改为其他方法。

【问题讨论】:

  • 为什么要使用尽可能少的行?为什么不追求简洁而不是可读性?
  • @Cyphase 感谢您的回答。实际上,该函数还执行许多其他操作,因此我希望将其保持在尽可能少的行数以提高可读性。如果您愿意,您还可以将“非简短”版本添加到您的答案中。谢谢!
  • @Cyphase Performance,因为搜索被执行了两次。
  • “为了便于阅读,我想尽可能少写几行”。尽可能少的行数不一定等于可读性。事实上,通常不会。
  • 你为什么不告诉我们你当时真正想要做什么,这样我们才能更好地回答? :)

标签: python regex pandas lambda


【解决方案1】:

你可以这样做:

f1 = lambda x: dictionary.get(regex.findall(x)[0], '') if len(regex.findall(x)) > 0 else ""
f2 = lambda x: dictionary.get(regex.search(x).group(2), '') if regex.search(x) else ''

但我建议不要尝试将其塞进lambda。除了可读性问题之外,您每次都要进行两次搜索。最好使用def 定义您需要的函数。

事实上,鉴于您只调用一次函数,在您定义它们的函数内,您可以直接将代码放入fruit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-09
    • 2018-04-19
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多