Skip to main content
 首页 » 编程设计

python之使用正则表达式将自由文本解析为字典

2024年08月15日43qlqwjy

我正在尝试使用正则表达式将这种类型 自由文本转换为字典。

alamine A (12 000 UI/kg), thiamine D3 (1 200 UI/kg), niacine E (70 mg/kg), zinc [sous forme d'oxyde de zinc] (70 mg/kg), zinc [sous forme de chélate de zinc d'acides aminés, hydraté] (45 mg/kg), copper [sous forme de sulfate de cuivre (II), pentahydraté] (10 mg/kg), iode [sous forme d'iodate de calcium, anhydre] (2 mg/kg), sélénium [sous forme de sélénite de sodium] (0.2 mg/kg), cyaobactin12 (0.2%)

思路是捕获key和value

  • key : alamine A
  • 值:12 000 UI/kg

或

  • 关键:铜[sous forme de sulfate de cuivre (II), pentahydraté]
  • 值:10 mg/kg

我尝试通过选项来实现这种文本转换:

第一种方法:直接使用正则表达式 (()\((\d*\.*\s*\d*\s*)(UI\/kg|mg\/kg|%)\))但我只能正确隔离值而不是 key 。

第二种方法:

  1. 用这种正则表达式 (\[.*),(.*\] 去掉方括号内的 ',',它不能准确捕获 [sous forme de sulfate de cuivre (II), pentahydraté] 或 [sous forme d'iodate de calcium**,** anhydre]
    1. 沿“,”拆分,使列表看起来像列表 ["alamine A (12 000 UI/kg)","thiamine D3 (1200 UI/kg)"...] 3.对于列表中的每个元素,使用更简单的正则表达式作为第一种方法 (.*)\((\d*\.*\s*\d*\s*)(UI\/kg|mg\/kg |%)\))

我应该如何进行?

请您参考如下方法:

让我们从更简单的部分开始:值(value)。 它是用括号括起来的东西:(?P<value>\([^)]+\))

(?P<value> # Capturing "value" group 
  \(       # Matches an opening parentheses 
  [^)]+    # Matches one or more non ")" characters 
  \)       # Matches a closing parentheses 
) 

完成后,我们来处理 key 。
这里有一点, key 可能包括一些用方括号括起来的文本。
然后是任何非 (或 [字符,后面可以跟括号中的任何内容:(?P<key>[^[(]+(?:\[[^]]+\])?)

(?P<key>  # Capturing "key" group 
  [^[(]+  # One or more non "(" or "[" characters 
  (?:     # Non-capturing group 
    \[    # An opening bracket 
    [^]]+ # One or more non "]" characters 
    \]    # A closing bracket 
  )?      # Non-capturing group made optional 
) 

工作快完成了。
我们将添加一个 \s在我们两个小组之间作为他们之间的分隔符。
最后,让我们处理系列分隔符:(?:(?<=,\s)|^)

(?:        # Non-capturing group 
  (?<=,\s) # Either preceded by a coma and a space 
  |^       # Or alternatively beginning the string 
) 

现在把它们放在一起: (?:(?<=,\s)|^)(?P<key>[^[(]+(?:\[[^]]+\])?)\s(?P<value>\([^)]+\))