是否有任何优雅的方法可以将文本按单词拆分并保留单词。尽管有一些关于使用 re 包和模式拆分的工作,例如(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]