【问题标题】:Special re.sub python3特殊 re.sub python3
【发布时间】:2016-12-02 04:54:25
【问题描述】:

我想做一些特别的 re.sub 输入

string = "\"hope\" and \"love\" or \"passion\" and (\"luck\" or \"money\") "
word_list = ['hope', 'love', 'passion', 'money', 'luck']

希望的输出是

'0 and 1 or 2 and (4 or 3)

我试试

print(re.sub("\"([^\"]*)\"", stri.index(r'\g<1>') , string))

但是没有用

【问题讨论】:

  • 不要全部转义,请使用单引号。

标签: python regex python-3.x


【解决方案1】:

使用re.sub 函数和替换 函数作为第二个参数:

string = "\"hope\" and \"love\" or \"passion\" and (\"luck\" or \"money\") "
word_list = ['hope', 'love', 'passion', 'money', 'luck']

print(re.sub("\"([^\"]*)\"", lambda m:
    str(word_list.index(m.group(1))) if m.group(1) in word_list else m.group(1), string))

输出:

0 and 1 or 2 and (4 or 3) 

请记住,可能存在不在word_list 列表中的匹配项,例如... (\"luck\" or \"money\") or \"compassion\"

re.sub(模式、repl、字符串、count=0、flags=0)

... 如果 repl 是一个函数,它会为每个不重叠的函数调用 模式的发生。该函数采用单个匹配对象 参数,并返回替换字符串。

【讨论】:

    【解决方案2】:

    或者(没有re),您可以使用enumerate 迭代word_list,并使用str.replace() 替换string 的内容为:

    my_string = "\"hope\" and \"love\" or \"passion\" and (\"luck\" or \"money\") "
    word_list = ['hope', 'love', 'passion', 'money', 'luck']
    
    for i, word in enumerate(word_list):
        my_string = my_string.replace('"{}"'.format(word), str(i))
    

    my_string 持有的最终值将是:

    '0 and 1 or 2 and (4 or 3) '
    

    【讨论】:

      【解决方案3】:

      无需考虑您的单词列表,您可以使用itertools.count 来计算匹配数,并使用一个函数作为sub() 函数的第二个参数,该函数为每个匹配调用计数器的next

      In [10]: from itertools import count
      
      In [11]: c = count()
      
      In [12]: re.sub(r'"([^"]+)"', lambda x: str(next(c)), string)
      Out[12]: '0 and 1 or 2 and (3 or 4) '
      

      如果您希望索引基于word_list 中的单词索引作为一种有效的方法,您可以创建字典,将单词作为键,索引作为值,然后使用简单的索引来获取 @ 中的相应索引987654326@函数:

      In [29]: word_dict = {w: str(i) for i, w in enumerate(word_list)}
      
      In [30]: re.sub(r'"([^"]+)"', lambda x: word_dict[x.group(1)], string)
      Out[30]: '0 and 1 or 2 and (4 or 3) '
      

      请注意,您可以使用list.index 方法来访问每个单词的单词索引。但是由于列表索引的复杂性是 O(n),它不如使用 O(1) 的字典索引那么有效。

      【讨论】:

      • 非常好用,但是我不明白 x.group(1) 的作用是什么
      • @SlimaneMEHARZI 它将为您提供每个匹配项的第一个捕获组,这将是与捕获组之间的正则表达式匹配的字符串 ([^"]+)。
      猜你喜欢
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 2018-04-29
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      相关资源
      最近更新 更多