首页 > 解决方案 > 检查字符串是否遵循python正则表达式中的特定字符串列表

问题描述

我有一个字符串列表,我称之为“text_sentences”类型

["bla bla bla", "yada yada yada","foo boo, foo"...]

然后我有一个特定字符串(单词)的列表,我必须用它来识别我的元素(句子),text_sentences我称之为“单词”

words=["word1", "word2",..]

我的目标是根据 来识别句子text_sentenceswords即如果一个句子至少包含 中的一个单词words,则该句子(的元素text_sentences)将被放入一个新列表中,说它“匹配”。如果没有,请将其放入名为“不匹配”的列表中。我可以用类似的东西重现这个

    matched=[]
    unmatched_sent=[]
    for j in range(len(text_sentences)):
        if any(s in text_sentences[j] for s in words):
            matched.append(text_sentences[j])
        else:
            unmatched.append(text_sentences[j])

但是:这只是我需要执行的过程的一个步骤。事实上,我也有一个类型的否定词列表

negations=["no","not","none"]

它的用途如下:如果 text_sentences 中的一个句子在 words 中至少包含一个单词,那么该句子必须附加到matched列表中;但是,如果words该句子中包含的单词 from that 跟在negations列表中的任何单词之后,则必须将该句子附加到列表中unmatched。如果句子不包含任何单词 from words,那么它必须附加到unmatched。我怎样才能一次完成这一切?

标签: pythonregexlist

解决方案


t = ["bla bla bla", "yada yada yada","foo boo, foo", "yoo no you are not in list"]
words = ["test", "bla", "yoo"]
negation = ["no","not","none"]
unmatched = []
matched = []
for i in words:
    for j in t:
        if i in j:
            matched.append(j)

for l in t:
    if l not in matched and l not in unmatched:
        unmatched.append(l)

for m in negation:
    for k in matched:
        if m in k:
            matched.remove(k)

print(unmatched)
print(matched)

推荐阅读