【问题标题】:Replacing abbreviations from dictionary替换字典中的缩写
【发布时间】:2015-01-24 03:26:28
【问题描述】:

我有一个类似于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

用另外三行引用相同的示例字典

rna,ribonucleic acid
rnd,radical neck dissection
rni,recommended nutrient intake
rnp,ribonucleoprotein
m,months
m,male
y,years

我想在逻辑上替换它,例如,数字后跟 m(数字和字母 'm' 之间有或没有空格,与 'y' 年类似)将是月,而字符后跟 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

【问题讨论】:

  • 区分一个“m”(月)和另一个“m”(男性)是相当困难的。
  • @snotna 我很肯定,可以使用正则表达式来完成,我真的不擅长。

标签: python regex csv dictionary replace


【解决方案1】:

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

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2022-06-30
    • 2022-01-07
    • 1970-01-01
    • 2023-01-23
    相关资源
    最近更新 更多