将字符串从科学文章关键字拆分为关键字列表

2024-10-17 06:28:58 发布

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

我试图用逗号作为分隔符从关键字字符串中拆分每个关键字,但是化学名称也用逗号命名,如何识别化学名称而不分隔名称?你知道吗

这里有一些例子:

keywords_string1 = "Forecasting,GM(1,1),Background value"
#expected result1 : [ "Forecasting", "GM(1,1)", "Background value" ]

keywords_string2 = "(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene, ultrasonic sprayer"
#expected result2 : [ "(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene", "ultrasonic sprayer" ]

Tags: 名称value关键字backgroundexpected逗号化学keywords
1条回答
网友
1楼 · 发布于 2024-10-17 06:28:58

如果我们能确定没有名字以数字结尾(据我所知,是(?),您可以在逗号(及其最终的周围空格)上拆分,这些逗号前面没有数字。你知道吗

使用正则表达式,我们可以:

import re

def split_on_commas(s):
    split_pattern = re.compile('(?<=\D) *, *')
    return split_pattern.split(s)

它给出了测试用例的预期结果:

keywords_string1 = "Forecasting,GM(1,1),Background value"
#expected result1 : [ "Forecasting", "GM(1,1)", "Background value" ]

print(split_on_commas(keywords_string1))
# ['Forecasting', 'GM(1,1)', 'Background value']


keywords_string2 = "(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene, ultrasonic sprayer"
#expected result2 : [ "(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene", "ultrasonic sprayer" ]

print(split_on_commas(keywords_string2))
#['(3E)-4, 8-Dimethyl-1, 3, 7-nonatriene', 'ultrasonic sprayer']

注意,我们必须对regex中的非数字使用正向lookback断言(?<=\D),这样就不会将非数字字符作为分割模式的一部分捕获。你知道吗

相关问题 更多 >