首页 > 解决方案 > 如何根据来自不同列表的单词匹配拆分字符串?

问题描述

我有一个字符串。现在,如果两个不同列表中的任何内容匹配,我想将字符串拆分为多个部分。我怎样才能做到这一点 ?我有什么。

dummy_word = "I have a HTML file"
dummy_type = ["HTML","JSON","XML"]
dummy_file_type = ["file","document","paper"]

for e in dummy_type:
    if e in dummy_word:
        type_found = e
        print("type ->" , e)
        dum = dummy_word.split(e)
        complete_dum = "".join(dum)

        for c in dummy_file_type:
            if c in complete_dum:
                then = complete_dum.split("c")
                print("file type ->",then)

在给定的场景中,我的预期输出是["I have a", "HTML","file"]

标签: pythonarrayslistre

解决方案


这对我有用:

dummy_word = "I have a HTML file"
dummy_type = ["HTML","JSON","XML"]
dummy_file_type = ["file","document","paper"]

temp = ""
dummy_list = []
for word in dummy_word.split():
    if word in dummy_type or word in dummy_file_type:
        if temp:
            dummy_list.append(temp)
            print(temp, "delete")

        print(temp)
        new_word = word + " "
        dummy_list.append(new_word)
        temp = ""
    else:
        temp += word + " "
    print(temp)
print(dummy_list)

推荐阅读