从字典中替换缩略语

2024-07-03 08:04:50 发布

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

我有一个类似于this question的问题。但我还有一个问题。从下面的问题中获取同一个表,我添加了几行。在

A,B,C,D
RNA,lung cancer,15,biotin
RNA,lung cancer,15,biotin
RNA,breast cancer,15,biotin
RNA,breast cancer,15,biotin
RNA,lung cancer,15,biotin
65 y 4m,prostate cancer,biotin
m,lung cancer,biotin

引用同一个字典的三行

^{pr2}$

我想逻辑地替换它,例如,一个数字后跟m(数字和字母‘m’之间有或没有空格,类似地‘y’year)将是月份,而后面跟m或单个m的字符将是男性(而不是月份,因为m代表月份在字典中首先出现)。我希望我的最终输出是

A,B,C,D
ribonucleic acid,lung cancer,15,biotin
ribonucleic acid,lung cancer,15,biotin
ribonucleic acid,breast cancer,15,biotin
ribonucleic acid,breast cancer,15,biotin
ribonucleic acid,lung cancer,15,biotin
65 years 4months,prostate cancer,biotin
male,lung cancer,biotin

Tags: 字典数字逻辑thisrnaquestion月份cancer
1条回答
网友
1楼 · 发布于 2024-07-03 08:04:50

对于要进行的每个替换,定义一个模式和一个替换字符串。使模式捕获紧跟在要替换的文本之前的文本。在进行替换时可以使用该文本。像这样:

import re

month_pair = (re.compile('(\d\s*)m'), 'months')
year_pair = (re.compile('(\d\s*)y'), 'years')

def substitute(s, pairs):
  for (pattern, substitution) in pairs:
    match = pattern.search(s)
    if match:
      s = pattern.sub(match.group(1)+substitution, s)
  return s

pairs = [month_pair, year_pair]
print(substitute('65 y 4m', pairs))

相关问题 更多 >