如何使用 python 中预定义的词组将字符串中的词分组为不同的字符串?

How to group words of a string into different strings using pre-defined word groups in python?

我想将一个包含如下单词的字符串转换为 3 个字符串,其中第一个包含 The Red Fox,第二个包含 The Cat,最后一个包含 The Dog最后一个是蓝色的。 更简单的解释,它应该是这样的:

#    String0 = The Red Fox The Cat The Dog Is Blue
# The line above should transform to the lines below
#    String1 = The Red Fox
#    String2 = The Cat
#    String3 = The Dog Is Blue

您必须注意,构成表达式的词是要改变的(但仍会形成已知的表达式),所以我正在考虑制作一本字典,这将有助于识别这些词并定义它们应该如何组合在一起,如果它是可以的。

我希望我能被理解,并且有人能回答我的问题。

这为您提供了所需的基本代码:

def separate():
    string0 = "The Red Fox The Cat The Dog Is Blue"
    sentences = ["The "+sentence.strip() for sentence in string0.lower().split("the") if sentence != ""]
    for sentence in sentences:
        print(sentence)

您可以使用正则表达式:

import re

string = "The Red Fox The Cat The Dog Is Blue"
# create a regex by joining your words using pipe (|)
pattern = "(The(\s(Red|Fox|Cat|Dog|Is|Blue))+)"  
print([x[0] for x in re.findall(pattern, string)])  # ['The Red Fox', 'The Cat', 'The Dog Is Blue']

在上面的示例中,您可以根据您拥有的单词列表动态创建您的模式。

编辑:动态构建模式:

pattern = f"(The(\s({'|'.join(list_of_words)}))+)"