使用re 库。不区分大小写时,在其中使用flags=re.I 选项。
import re
acronyms=[' MRI', 'fMRI', 'PPE', 'FFE']
text="""pull porous experiment
public protection expertise
personal protective
equipment
here is a magnetic resonance interglobular section
with a certain energy measure is on a table"""
matched={}
for a in acronyms:
pattern=''
for letter in a.strip():
pattern+='[ ]*{}[^ \n]+[ \n]+'.format(letter)
pattern+=''
print(a.strip(),pattern)
matched.update({a.strip():re.findall(pattern,text,flags=re.I)})
print(matched)
matched 现在应该包含一个字典,其中包含每个首字母缩写词和每个首字母缩写词的匹配列表。
输出 matched 现在是(注意首字母缩略词已去除前导和尾随空格)
{'MRI': [' magnetic resonance interglobular '], 'fMRI': [], 'PPE': ['pull porous experiment\n ', 'public protection expertise\n', 'personal protective \nequipment\n'], 'FFE': []}
这允许结果跨越多行,但那些行尾字符 (\n) 会包含在匹配结果中。如果您更喜欢那些是空格,您可以使用例如re.sub 将[\n ]+ 替换为。
这是re 库的参考:https://docs.python.org/3/library/re.html。这是正则表达式的许多可能有用的通用解释之一:https://docs.python.org/3/howto/regex.html#regex-howto。