首页 > 解决方案 > Python根据几个标记拆分一个集合

问题描述

我想根据几个关键字拆分一个句子:

p = r'(?:^|\s)(standard|of|total|sum)(?:\s|$)'
re.split(p,'10-methyl-Hexadecanoic acid of total fatty acids')

这输出:

['10-methyl-Hexadecanoic acid', 'of', 'total fatty acids']

预期产量:['10-甲基-十六烷酸', 'of', 'total', '脂肪酸']

我不确定为什么要注册。表达式不会根据令牌“总计”进行拆分。

标签: pythonregexsplit

解决方案


您可以使用

import re
p = r'(?<!\S)(standard|of|total|sum)(?!\S)'
s = '10-methyl-Hexadecanoic acid of total fatty acids'
print([x.strip() for x in re.split(p,s) if x.strip()])
# => ['10-methyl-Hexadecanoic acid', 'of', 'total', 'fatty acids']

查看Python 演示

细节

  • (?<!\S)(standard|of|total|sum)(?!\S)当用空格括起来或在字符串开始/结束处时,将匹配并捕获到组中的第 1 组单词。
  • 理解将有助于摆脱空白项 ( if x.strip()) 并x.strip()从每个非空白项中修剪空白。

推荐阅读