繁体   English   中英

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

[英]How to group words of a string into different strings using pre-defined word groups in 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

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

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

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

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)}))+)"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM