首页 > 解决方案 > 关于python正则表达式的一些事情

问题描述

最近看了一篇关于数据科学的文章,有一点让我很困惑。它是一个'x.group()'的用法。我还是看不懂。我会在下图中展示它。
代码是这样的:

import re
negations_dic = {"isn't":"is not", "aren't":"are not", "wasn't":"was not", "weren't":"were not"}
lower_case = "I isn't a sds"
neg_pattern = re.compile(r'\b(' + '|'.join(negations_dic.keys()) + r')\b')
neg_handled = neg_pattern.sub(lambda x: negations_dic[x.group()], lower_case)
print(neg_handled)

这是关于这个问题的图片。希望有人能帮助我。

标签: python

解决方案


  1. lambda功能_

Lambda 函数只是在表达式中定义函数的一种方式。您可以将代码替换为以下代码,使用经典函数且不带 lambda(因此代码中不带“x”):

import re

def func(m):
    return negations_dic[m.group()]

negations_dic = {"isn't":"is not", "aren't":"are not", "wasn't":"was not", "weren't":"were not"}
lower_case = "I isn't a sds"
neg_pattern = re.compile(r'\b(' + '|'.join(negations_dic.keys()) + r')\b')
neg_handled = neg_pattern.sub(func, lower_case)

print(neg_handled)
  1. sub()方法_

sub()以下是有关方法 的 Python 文档摘录:

sub(repl, string)
返回通过替换 repl 替换 string 中最左侧不重叠出现的模式获得的字符串。[...] 如果 repl 是一个函数,它会在每个不重叠的模式出现时调用。该函数采用单个匹配对象参数,并返回替换字符串。

在您的代码中,参数repl是一个函数:它将用正则表达式捕获的每个匹配对象替换为字典中对应的值negations_dic

  1. match.group()方法_

match.group()以下是有关方法 的 Python 文档摘录:

match.group([group1, ...])
返回匹配的一个或多个子组。
如果只有一个参数,则结果是单个字符串 [...]
没有参数, group1 默认为零(返回整个匹配项)。
如果 groupN 参数为零,则对应的返回值是整个匹配字符串;如果在包含范围 [1..99] 内,则为匹配相应括号组的字符串。

这解释了你的结果,即:

  • x.group()相当于x.group(0)
  • x.group(0)返回整个比赛:is'nt
  • x.group(1)返回匹配第一个括号组的字符串:is'nt
  • x.group(2)返回错误,因为没有第二个带括号的组。

此外,这是一个示例,re.search用于更好地理解group()工作方式:

import re

m = re.search(r'((2nd) and (3rd) group)', '2nd and 3rd group')

print(m.group())  # it prints "2nd and 3rd group"
print(m.group(0)) # it prints "2nd and 3rd group"
print(m.group(1)) # it prints "2nd and 3rd group"
print(m.group(2)) # it prints "2nd"
print(m.group(3)) # it prints "3rd"
print(m.group(4)) # it returns an error `IndexError: no such group` because there is no 4th group
  1. 您应该阅读并了解更多关于rePython 中的 lambda 函数的信息。

推荐阅读