python - 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', '脂肪酸']
我不确定为什么要注册。表达式不会根据令牌“总计”进行拆分。
解决方案
您可以使用
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']
细节
(?<!\S)(standard|of|total|sum)(?!\S)
当用空格括起来或在字符串开始/结束处时,将匹配并捕获到组中的第 1 组单词。- 理解将有助于摆脱空白项 (
if x.strip()
) 并x.strip()
从每个非空白项中修剪空白。
推荐阅读
- authentication - 分布式系统中的共享访问令牌
- google-apps-script - 谷歌脚本依赖下拉列表 - 不工作
- python - 如何制作一个在 python 中更改频道名称的机器人?
- php - 为 $_GET 请求创建页面
- java - 如何在 DDD 中命名域服务
- python - 在某些条件下,找到两个数组之间(逐项)比率的最大值或最小值
- javascript - Zapier 还是自己动手?
- python - AJAX 问题(网络抓取)- 需要建议 :)
- php - JSON:使用 PHP 将数组附加到数组中
- javascript - Django 在 POST 请求中返回 500