我想要一种使用单词列表作为分隔符来拆分字符串列表的有效方法。输出是另一个字符串列表。
我在一行中尝试了多个.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']发布于 2019-05-09 22:54:57
你可以像这样使用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']https://stackoverflow.com/questions/56062170
复制相似问题