【问题标题】:How to conditional delete regex如何有条件地删除正则表达式
【发布时间】:2020-05-09 20:42:54
【问题描述】:

我正在尝试处理 word 文件,我必须对此进行总结:

str = '''red (5), blue (3 left, right, up), green(2 one, two, three), yellow(7)'''

到这里:

{red:5, blue:3, green:2, yellow:7}

只有括号中的数值对我很重要。

我尝试过处理一些长代码,但效果不佳,所以基本上,我想要一个简单的解决方案,例如:

# discard everything else in bracket except for the numeric value
re.replace(r'(.)', '**NUMERIC VALUE**', str)
# also split based on a ',' that is outside the bracket
re.compile('\),').split('str')

我无法弄清楚 *NUMERIC VALUE** 部分以及如何根据正则表达式进行条件拆分 提前感谢您的帮助

【问题讨论】:

  • 缺少详细信息。是否保证数字始终是括号内的第一个也是唯一的第一个元素?
  • 数字总是第一个,我总是想要第一个数字,因为在某些情况下,括号内还有数字后面的日期,

标签: python regex string nlp


【解决方案1】:

此脚本会为您的问题中的字符串生成所需的结果,但需要对真实数据进行更多测试:

import re

s = '''red (5), blue (3 left, right, up), green(2 one, two, three), yellow(7)'''

d = dict(re.findall(r'([a-z]+)\s*\(.*?(\d+)', s))

print(d)

打印:

{'red': '5', 'blue': '3', 'green': '2', 'yellow': '7'}

【讨论】:

  • 只需少量编辑,即可完美运行。非常感谢。不过有一件事 - 你是如何在最后一部分用数值替换正则表达式的 '(.*?(\d+)'
  • @JaySabir 也许我不明白 - 我用正则表达式组创建 2 元素元组,第一组是颜色名称,第二组是数字(因此 \d+)。然后我喂这些元组做dict()构造函数来获取字典。
【解决方案2】:

这是否解决了您的问题:https://regex101.com/r/QQ19Qi/1

import re

regex = r"(.*)\ ?\((\d+).*\).*"

test_str = "red (5), blue (3 left, right, up), green(2 one, two, three), yellow(7)"

subst = "\\1:\\2"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2019-02-13
    • 2011-10-30
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多