首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当包含特定字符时,使用变量不工作的python正则表达式

当包含特定字符时,使用变量不工作的python正则表达式
EN

Stack Overflow用户
提问于 2022-05-19 12:04:25
回答 1查看 40关注 0票数 2

我正在研究一些药物的数据收集,我想从产品描述中提取整个句子中的剂量。每种活性物质(DCI)都有一个剂量,这些物质都是在一份清单中输入的。每个DCI的剂量通常是在description中其名称之后。

我在用:

代码语言:javascript
复制
teste=[]
for x in listofdci:
   teste2 = [f"{x}{y}" for x,y in re.findall(rf"(?:{x})\s*(\d+(?:[.,]\d+)*)\s*(g|mg|)",strength)]
   teste.extend(teste2)

除了变量包含()+的情况外,它工作得很好,例如:

代码语言:javascript
复制
listofdci = [' Acid. L(+)-lacticum D4']
description = ' Acid. L(+)-lacticum D4 250 mg'
#error: nothing to repeat

#

listofdci = ['Zinkoxid', '(+/–)-α-Bisabolol', 'Lebertran (Typ A)', 'Retinol (Vitamin A)', 'Colecalciferol (Vitamin D3)']
description = 'Zinkoxid 13 g, (+/–)-α-Bisabolol 0,026 g (eingesetzt als Dragosantol-Zubereitung), Lebertran (Typ A) 5,2 g, Retinol (Vitamin A) 24,5 mg (entspr. 41 600 I.E. Retinolpalmitat [enth. Butylhydroxyanisol, Butylhydroxytoluol]), Colecalciferol (Vitamin D3) 10,4 mg (entspr. 10 400 I.E. mittelkettige Triglyceride [enth. all-rac-α-Tocopherol])'
#error: nothing to repeat
#Here he collects the first dosage -> ['13g'] and then outputs the error

#

listofdci = [' Efeublätter-Trockenextrakt']
description = ' Efeublätter-Trockenextrakt (5-7,5:1) 65 mg - Auszugsmittel: Ethanol 30% (m/m)'
#[]
#here it outputs an empty list

理想情况下,我想拥有:

代码语言:javascript
复制
listofdci = [' Acid. L(+)-lacticum D4']
description = ' Acid. L(+)-lacticum D4 250 mg'
#['250mg']

#

listofdci = ['Zinkoxid', '(+/–)-α-Bisabolol', 'Lebertran (Typ A)', 'Retinol (Vitamin A)', 'Colecalciferol (Vitamin D3)']
description = 'Zinkoxid 13 g, (+/–)-α-Bisabolol 0,026 g (eingesetzt als Dragosantol-Zubereitung), Lebertran (Typ A) 5,2 g, Retinol (Vitamin A) 24,5 mg (entspr. 41 600 I.E. Retinolpalmitat [enth. Butylhydroxyanisol, Butylhydroxytoluol]), Colecalciferol (Vitamin D3) 10,4 mg (entspr. 10 400 I.E. mittelkettige Triglyceride [enth. all-rac-α-Tocopherol])'
#['13g','0,026','5,2g','24,5','10,4']

#

listofdci = [' Efeublätter-Trockenextrakt']
description = ' Efeublätter-Trockenextrakt (5-7,5:1) 65 mg - Auszugsmittel: Ethanol 30% (m/m)'
#[65mg]

除了可能将每个()+从数据集中移除之外,我不知道如何避开这个特定的问题。此外,因为这些字符可以出现在字符串的每个部分,所以我认为我无法使用集合来识别它们:'[]‘

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-19 13:18:20

如果关键字和数字之间的括号内有一个可选的子字符串,则可以使用

代码语言:javascript
复制
teste=[]
for x in listofdci:
    test2 = [f"{x}{y}" for x,y in re.findall(rf"{re.escape(x)}(?:\s*\([^()]*\))?\s*(\d+(?:[.,]\d+)*)\s*(m?g\b|)", description)]
    if test2:
        teste.extend(test2)

Python演示

详细信息

  • {re.escape(x)} -转义关键字
  • (?:\s*\([^()]*\))? -一个可选的序列,包括零或多个空白空间、(、除()之外的零或多个字符,然后是)
  • \s* -零或多个空白空间
  • (\d+(?:[.,]\d+)*) -一个或多个数字,然后是零或多个. / ,序列和一个或多个数字。
  • \s* -零或多个空白空间
  • (m?g\b|) - mmg作为整词,或空字符串.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72304224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档