按特定单词或短语拆分文本,并将该单词保存在Python中



有没有一种优雅的方法可以通过一个单词分割文本并保留单词。尽管有一些关于使用重新打包和类似模式(Python re库String split,但将分隔符/分隔符作为下一个字符串的一部分(进行拆分的方法,但当分隔符重复多次时,这些方法都不适用于这种情况。例如:

s = "I want to split text here, and also keep here, and return all as list items"

使用分区:

s.partition("here")
>> ('I want to split text ', 'here', ', and also keep here, and return all as list items')

使用re.split((:

re.split("here",s)
>> ['I want to split text ', ', and also keep ', ', and return all as list items']

所需的输出应该是以下列表中的内容:

['I want to split text', 'here', ' , and also keep ', 'here', ' , and return all as list items']

是。您要查找的是re.split()方法的一个特性。如果在表达式中使用捕获组,它也会返回匹配的术语:

import re
s = "I want to split text here, and also keep here, and return all as list items"
r = re.split('(here)', s)
print(r)

结果:

['I want to split text ', 'here', ', and also keep ', 'here', ', and return all as list items']

如果定义了多个捕获组,则会分别返回每个捕获组。因此,您可以只返回分隔符的一部分,或者返回每个分隔符的多个部分。我过去用这个功能做过一些相当疯狂的事情。它可以替换大量原本需要的代码。

使用re无疑是最好的方法,但您也可以递归地扩展partition()方法。

def partitions(whole_string, split_string):
parts_tuple = whole_string.partition(split_string)
return [parts_tuple[0], parts_tuple[1], *partitions(parts_tuple[2], split_string)] if parts_tuple[1] else [whole_string]

最新更新