如何在Python中使用多个单词分隔符拆分字符串?

2024-06-01 00:51:12 发布

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

我想要一种有效的方法来拆分字符串列表,使用单词列表作为分隔符。输出是另一个字符串列表。你知道吗

我在一行中尝试了多个.split,这不起作用,因为第一个.split返回一个列表,后面的.split需要一个字符串。你知道吗

以下是输入:

words = ["hello my name is jolloopp", "my jolloopp name is hello"]
splitters = ['my', 'is']

我希望输出是

final_list = ["hello ", " name ", " jolloopp", " jolloopp name ", " hello"]

注意空格。你知道吗

也有可能有类似

draft_list = [["hello ", " name ", " jolloopp"], [" jolloopp name ", " hello"]]

可以使用numpy reshape(-1,1)之类的方法将其展平,得到final_list,但理想的情况是

ideal_list = ["hello", "name", "jolloopp", "jolloopp name", "hello"]

其中空格已被剥离,这类似于使用.strip()。你知道吗

编辑1:

如果单词分隔符是其他单词的一部分,那么使用re.split并不能完全起作用。你知道吗

words = ["hellois my name is myjolloopp", "my isjolloopp name is myhello"]
splitters = ['my', 'is']

那么输出就是

['hello', '', 'name', '', 'jolloopp', '', 'jolloopp name', '', 'hello']

应该什么时候

['hellois', 'name', 'myjolloopp', 'isjolloopp name', 'myhello']

这是使用re.split解决方案的已知问题。你知道吗

编辑2:

[x.strip() for x in re.split(' | '.join(splitters), ''.join(words))]

输入为空时无法正常工作

words = ["hello world", "hello my name is jolloopp", "my jolloopp name is hello"]

输出变为

['hello worldhello', 'name', 'jolloopp', 'jolloopp name', 'hello']

当输出应该

['hello world', 'hello', 'name', 'jolloopp', 'jolloopp name', 'hello']

Tags: 方法字符串namerehello列表ismy
1条回答
网友
1楼 · 发布于 2024-06-01 00:51:12

你可以用re比如

使用@pault建议的更好的方式更新,使用单词边界\b而不是:space:

>>> import re
>>> words = ['hello world', 'hello my name is jolloopp', 'my jolloopp name is hello']

# Iterate over the list of words and then use the `re` to split the strings,
>>> [z for y in (re.split('|'.join(r'\b{}\b'.format(x) for x in splitters), word) for word in words) for z in y]
['hello world', 'hello ', ' name ', ' jolloopp', '', ' jolloopp name ', ' hello']

相关问题 更多 >