【问题标题】:Regex Search with commas带逗号的正则表达式搜索
【发布时间】:2020-04-27 03:22:58
【问题描述】:

在正则表达式方面需要一些帮助。

str = 'label1 a1,832,b2 and label2 2, c45'

尝试将结果返回为

['label a1',label 832','label b2','label 2', 'label c45']

目前只能得到['label2 a1','label2 2']

谢谢!

编辑:

澄清一下。

我有一个标签列表

labelList = ['dog','cat','mouse',...]

str = 'There are 3 locations which are dog 122, h25 and cat a3.'

结果应该是:

result = 'dog 122', 'dog h25' and 'cat a3'.

目前我正在进行正则表达式搜索:

for x in labelList:
    re.search(r'\b(%s) ([^ \r\n]+\b')

希望这能澄清问题!

编辑2:

labelList = ['dog','cat','mouse',...]

str = 'There are 3 locations which are dog 122, h25 and cat a3.'

for x in labelList:

    if re.search(r'\b(%s)\b' % (x), str):

        nr = [f"(%s) {m}" % (x) for m in re.findall(r"(?:(%s))?(\w+)",  comText) if m!= 'and']
        print(nr)

但是,输出似乎是错误的。它给了我以下输出

["(dog) (' ','there')", "(dog) (' ','are')", "(dog) (' ', '3')" ... 

【问题讨论】:

  • 到目前为止只能得到...,你试图让你走到这一步的代码在哪里?
  • 如果您包含正则表达式,我们可以为您提供提示。
  • a18322c45 有一个共同的特点,即它们都紧跟在逗号之后或位于行尾。我们可以匹配\w+(?=,|$)b2 呢?告诉我们您也希望提取该字符串的 rule 是什么?您需要先用文字告诉我们匹配规则,然后举例说明。用一个例子陈述的问题很少是明确的,这也不例外。
  • 是给定的"label",还是字符串可以是'cat1 a1,832,b2 and cat2 2, c45',在这种情况下,您希望返回['cat a1', 'cat 832','cat b2', 'cat 2', 'cat c45']

标签: python regex search


【解决方案1】:

试试这个:

import re
str = 'label1 a1,832,b2 and label2 2, c45'
str = str.replace('and', ',')
str = re.sub(r"label[0-9]+", "", str)
labels = ['label {}'.format(x.strip()) for x in str.split(',')]

输出是:

labels = ['label a1', 'label 832', 'label b2', 'label 2', 'label c45']

在我看来,您将 label[0-9]+ 和子字符串 and 作为无用信息。 只需将其删除并提取标签名称即可。然后使用string.format()函数重构字符串

【讨论】:

  • 使用 f-strings 的语法会更简单。
【解决方案2】:

好的。到目前为止,我有一种方法可以提取一个标签后面的文本,直到一个句点或单词“and”。

>>> target_str = 'There are 3 locations which are dog 122, h25 and cat a3.'
>>> label_list = ['dog', 'cat', 'mouse', 'wombat']
>>> 
>>> expr = r"\b(" + '|'.join(label_list) + r")(.*?)(?:and|\.)"
>>>
>>> label_expr = re.compile(expr)  # Put somwhere it will only be compiled once.
>>>
>>> new_label_list = [f"{species} {tag}" 
...                   for species, tags in label_expr.findall(target_str)
...                   for tag in re.findall(r"\w+", tags)]
>>> new_label_list
['dog 122', 'dog h25', 'cat a3']
>>> 

标签分两个阶段提取。首先,我们得到一个元组列表,其中第一项是物种(狗,猫),第二项是标签(或标签)的原始列表。然后进行迭代以构建最终标签。

如果编译表达式,请将编译代码放在只需要执行一次的地方 - 否则编译它的意义何在。

或者使用.finditer() 代替.findall()

>>> new_label_list = [f"{m.group(1)} {tag}"
...                   for m in label_expr.finditer(target_str)
...                   for tag in re.findall(r"\w+", m.group(2))]
>>> new_label_list
['dog 122', 'dog h25', 'cat a3']

【讨论】:

  • 感谢您的回答!我有一个标签列表,其中 labelList = [label1, label2, label3...] 所以 label1 和 label2 是唯一的标签。那么我应该如何修改代码呢?
  • 如果以上不能处理所有情况@datajem,您可以发布更多必须解析的目标文本示例
  • 是的。谢谢。
  • 如果您发现任何解决方案有帮助,给他们点赞@datajem 并没有什么坏处 ;-)
  • 已尝试投票。低于 15 的声望不会反映在公开显示的分数上。谢谢托德!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多