使用python正则表达式模块将该值替换为以前出现的首字母缩略词

2024-06-26 00:10:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将前面的单词添加到句子的-number之前出现的-number。请检查输入字符串和预期的输出字符串以获得更多说明。我用静态方式尝试了regex的.replace.sub方法,这是一种被操纵的输出

输入字符串:

The acnes stimulated the mRNA expression of interleukin (IL)-1, -8, LL-37, MMP-1, -2, -3, -9, and -13 in keratinocytes.

预期的输出字符串:

The acnes stimulated the mRNA expression of interleukin (IL)-1, interleukin (IL)-8, LL-37, MMP-1, MMP-2, MMP-3, MMP-9, and MMP-13 in keratinocytes.

代码:

import re
string_a = "The acnes stimulated the mRNA expression of interleukin (IL)-1, -8, LL-37, MMP-1, -2, -3, -9, and -13 in keratinocytes."
regex1 = re.findall(r"[a-z]+\s+\(+[A-Z]+\)+-\d+\,\s+-\d\,+", string_a)
regex2 = re.findall(r"[A-Z]+-\d+\,\s+-\d\,\s+-\d\,\s+-\d\,\s+[a-z]+\s+-\d+", string_a)

Tags: andofthe字符串inilllexpression
1条回答
网友
1楼 · 发布于 2024-06-26 00:10:25

你可以用

import re
string_a = "The acnes stimulated the mRNA expression of interleukin (IL)-1, -8, LL-37, MMP-1, -2, -3, -9, and -13 in keratinocytes."
pattern = re.compile(r"\b([A-Za-z]+\s*\([A-Z]+\)|[A-Z]+)(\s*-\d+(?:,\s*-\d+)*)(?:,\s*and\s+(-\d+))?")
print( pattern.sub(lambda x: x.group(1) + f', {x.group(1)}'.join(map(str.strip, x.group(2).strip().split(','))) + (f', and {x.group(1)}{x.group(3)}' if x.group(3) else ''), string_a) )
# => The acnes stimulated the mRNA expression of interleukin (IL)-1, interleukin (IL)-8, LL-37, MMP-1, MMP-2, MMP-3, MMP-9, and MMP-13 in keratinocytes.

Python demoregex demo

详细信息

  • \b-字边界
  • ([A-Za-z]+\s*\([A-Z]+\)|[A-Z]+)-捕获组1:一个或多个ASCII字母,然后是零个或多个空格,(,一个或多个大写ASCII字母,以及一个)一个或多个大写ASCII字母
  • (\s*-\d+(?:,\s*-\d+)*)-捕获组2:零个或多个空格,-,一个或多个数字,然后是零个或多个逗号序列,零个或多个空格,-和一个或多个数字
  • (?:,\s*and\s+(-\d+))?-可选的非捕获组:逗号、零个或多个空格、and、一个或多个空格,然后是捕获组3:-、一个或多个数字

Group 1值在用作替换参数的lambda中的所有Group 2逗号分隔的数字前面

如果组3匹配,and+space+连接的组1和组3值被追加

相关问题 更多 >