【问题标题】:check if string follows specific list of strings in python regex检查字符串是否遵循python正则表达式中的特定字符串列表
【发布时间】:2020-09-20 19:14:56
【问题描述】:

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

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

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

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

我的目标是根据words识别text_sentences中的句子,即如果一个句子至少包含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 的单词跟在negationslist 中的任何单词之后,则必须将该句子附加到列表unmatched 中。如果句子不包含来自words 的任何单词,则必须将其附加到unmatched。我怎样才能一次完成这一切?

【问题讨论】:

  • 为前一个单词做一个变量,如果有一个匹配并且前一个单词是一个否定,则改为unmatch。

标签: python regex list


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2014-04-25
    • 2023-03-03
    相关资源
    最近更新 更多