首页 > 解决方案 > 根据字母计数检索带括号的缩写的定义

问题描述

我需要根据括号中的字母数来检索首字母缩写词的定义。对于我正在处理的数据,括号中的字母数对应于要检索的单词数。我知道这不是获取缩写的可靠方法,但在我的情况下它会是。例如:

String = '虽然家族健康史 (FHH) 被普遍认为是常见慢性病的重要风险因素,但执业护士 (NP) 很少考虑。

期望输出:家族健康史 (FHH)、执业护士 (NP)

我知道如何从字符串中提取括号,但之后我被卡住了。任何帮助表示赞赏。

 import re

 a = 'Although family health history (FHH) is commonly accepted as an 
 important risk factor for common, chronic diseases, it is rarely considered 
 by a nurse practitioner (NP).'

 x2 = re.findall('(\(.*?\))', a)

 for x in x2:
    length = len(x)
    print(x, length) 

标签: pythonregextexttext-parsingabbreviation

解决方案


使用正则表达式匹配来查找匹配开始的位置。然后使用 python 字符串索引来获取导致匹配开始的子字符串。按单词拆分子字符串,并获取最后 n 个单词。其中n是缩写的长度。

import re
s = 'Although family health history (FHH) is commonly accepted as an important risk factor for common, chronic diseases, it is rarely considered by a nurse practitioner (NP).'


for match in re.finditer(r"\((.*?)\)", s):
    start_index = match.start()
    abbr = match.group(1)
    size = len(abbr)
    words = s[:start_index].split()[-size:]
    definition = " ".join(words)

    print(abbr, definition)

这打印:

FHH family health history
NP nurse practitioner

推荐阅读