首页 > 解决方案 > 如何使用python中的预定义词组将字符串的单词分组为不同的字符串?

问题描述

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

#    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

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

我希望我是可以理解的,并且有人会回答我的问题。

标签: pythonstringword

解决方案


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

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)

推荐阅读