【问题标题】:Split strings on commas, 'and's, 'or's用逗号分隔字符串,'和,'或
【发布时间】:2020-11-24 01:26:54
【问题描述】:

我想从一个自然编写的字符串列表转到一个 python 列表。

示例输入:

s1 = 'make the cake, walk the dog, and pick-up poo.'
s2 = 'flour, egg-whites and sand.'

输出:

split1 = ['make the cake', 'walk the dog', 'pick-up poo']
split2 = ['flour', 'egg-whites', 'sand']

我想在逗号(和句点)、“and”和“or”上拆分字符串,同时删除拆分和空字符串。由于牛津逗号的使用缺乏标准化,我不能只使用逗号。

我尝试了以下方法:

import re
[x.strip() for x in re.split('([A-Za-z -]+)', s1) if x not in ['', ',', '.']]

这给出了:

['make the cake', 'walk the dog', 'and pick-up poo']

这很接近。但是对于s2,它给出了:

['flour', 'egg-whites and sand']

我可以跨元素进行一些后期处理,以通过(and|or) 不断拆分元素,但我真的很想用逗号、and's 和 or's 的集合来标记。

我尝试了一些花哨的正则表达式拆分来对 and 之类的内容进行负面展望,但它不想拆分那个词。

[x.strip() for x in re.split('([A-Za-z -]+(?!and))', s2) if x not in ['', ',', '.']]
[x.strip() for x in re.split('([A-Za-z -]+(?!\band\b))', s2) if x not in ['', ',', '.']]

这也给了

['flour', 'egg-whites and sand']

我意识到有很多边缘情况,但我觉得我已经接近了,只是错过了一些小东西。

【问题讨论】:

  • 您也可以考虑用例如替换所有目标标记而不是正则表达式逗号,然后根据逗号进行拆分,丢弃空格。

标签: python regex string tokenize


【解决方案1】:

你可以使用

\s*(?:\b(?:and|or)\b|[,.])\s*

请参阅regex demo。详情:

  • \s* - 0+ 个空格
  • (?:\b(?:and|or)\b|[,.]) - 整个单词 andor,或逗号/句点
  • \s* - 0+ 个空格

Python demo

import re
rx = re.compile(r"\s*(?:\b(?:and|or)\b|[,.])\s*")
strings = ["make the cake, walk the dog, and pick-up poo.", "flour, egg-whites and sand."]
for s in strings:
    print( list(filter(None, rx.split(s))) )

请注意,逗号或句点在后面或用数字括起来时通常会被“排除”,您可以考虑将[.,] 替换为[,.](?!\d)[,.](?!(?<=\d[,.])\d)

【讨论】:

    【解决方案2】:

    我认为你需要在通行证中处理这个问题:

    • 应用标点符号分割
    • 应用连词分割

    这适用于您提供的两个测试用例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多