gpt4 book ai didi

Python根据几个标记拆分一个句子

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:00 24 4
gpt4 key购买 nike

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

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-甲基-十六烷酸', '的', '总', '脂肪酸']

我不确定为什么 reg.表达式不会根据标记“总计”进行拆分。

最佳答案

你可以使用

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 demo

详情

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

关于Python根据几个标记拆分一个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57322379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com