【发布时间】: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