检索基于字母coun的带圆括号缩写的定义

2024-10-02 00:31:25 发布

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

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

尽管家庭健康史(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) 

Tags: 数据refor定义is家庭np字母
3条回答

一个想法,用recursive patternPyPI regex module一起使用。在

\b[A-Za-z]+\s+(?R)?\(?[A-Z](?=[A-Z]*\))\)?

See this pcre demo at regex101

  • \b[A-Za-z]+\s+匹配word boundaryone or morealpha,一个或多个空白
  • (?R)?递归部分:optionally从头开始粘贴模式
  • \(?需要使括号成为可选的,以便递归适合\)?
  • [A-Z](?=[A-Z]*\)将一个大写字母if followed by结束)与中间的任何A-Z匹配
  1. 不检查第一个单词字母是否与缩写中位置的字母匹配。在
  2. 不检查缩写前面的左括号。要进行检查,请添加可变长度的lookbehind。将[A-Z](?=[A-Z]*\))更改为^{}。在

使用regex匹配查找匹配开始的位置。然后使用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)

打印:

^{pr2}$

这能解决你的问题吗?在

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).'
splitstr=a.replace('.','').split(' ')
output=''
for i,word in enumerate(splitstr):
    if '(' in word:
        w=word.replace('(','').replace(')','').replace('.','')
        for n in range(len(w)+1):
            output=splitstr[i-n]+' '+output

print(output)

事实上,基廷比我早

相关问题 更多 >

    热门问题