在python中,如何在具有许多条件的'for'子句中找到精确匹配?

2024-09-28 23:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有以下列表:

full_text = ["This is Archie. He is a rare Norwegian Pouncing Corgo.", 
"This is Darla. She commenced a snooze mid meal.", 
"Here we have a majestic great"]

我想确定第一个子句包含“He”,第三个子句不包含“He”

但我不知道如何在这段代码中使用正则表达式:

gender = []

for f in full_text:
    words = f.split(" ")
    if any (["He" in f, "boy" in f, "him" in f, "his" in words]):
        gender.append(0)
    elif any (["She" in f, "girl" in f, "her" in f, "hers" in words]):
        gender.append(1)
    else:
        gender.append(-1)

我得到的结果是[0,1,1]。我想要的结果是[0,1,-1]


Tags: textin列表isanythisgenderfull
1条回答
网友
1楼 · 发布于 2024-09-28 23:22:36

Comment: .. due to case sensitivity to be more precise

我同意,更一般地说,你的常量,例如["he", "boy", "him", "his"]words["here", "we", "have"],应该都是小写的


Question: Can you show where you put in words?

gender = []

for f in full_text:
    words = f.split(" ")
    if any ([term in words for term in ["He", "boy", "him", "his"]]):
        gender.append(0)
    elif any ([term in words for term in ["She", "girl", "her", "hers"]]):
        gender.append(1)
    else:
        gender.append(-1)

print(gender)  
>>> [0, 1, -1]

OOP solution: Using early break.

class Gender:
    male = ["He", "boy", "him", "his"]
    female = ["She", "girl", "her", "hers"]

    def __init__(self, words):
        self.value = -1
        for value, terms in enumerate([Gender.male, Gender.female]):
            if self.match(words, terms):
                self.value = value
                break

    def match(self, words, terms):
        for term in terms:
            if term in words:
                return True
        return False      

gender = []

for f in full_text:
    words = f.split(" ")
    gender.append(Gender(words).value)

print(gender)  
>>> [0, 1, -1]

相关问题 更多 >