【发布时间】:2021-01-12 01:04:27
【问题描述】:
拥有["southnorth"] 等原始列表元素,我想根据["south", "north", "island"] 列表添加一个空格。然后,只要我们基于标记化的列表包含['south', 'north'],列表就会从['southnorth'] 更改为['south','north']。
但是,如果有一个列表 ["south", "island"],那么列表 ["southnorth"] 应该保持原样。
我的想法如下:
list1= ['southnorth']
#list2= ['south','north','island']
list2=['south','island']
str1= " ".join(list1)
str2= " ".join(list2)
Get the alternators to apply regex:
list_compound = sorted(list1 + list2, key=len)
alternators = '|'.join(map(re.escape, list_compound)
regex = re.compile(r''.format(alternators)
str1_split = re.sub(r'({})'.format(alternators),r'\1 ',str1,0, re.IGNORECASE)
str2_split = re.sub(r'({})'.format(alternators),r'\1 ',str2,0, re.IGNORECASE)
但是,上面的方法失败了,因为我需要确保序列的顺序。例如,要分解["southnorth"],我需要确保另一个列表有["south", "north"]。否则,保持原样。
【问题讨论】:
-
组合字符串中可以有两个以上的部分吗?
-
如果你的字符串是
southwestnorth怎么办?您希望输出是southwest north还是south westnorth? -
我会保留
southwestnorth的原始形式,因为标记化的唯一方法是south和north是连续的。
标签: python python-3.x regex tokenize