[英]How do I count how many times element in a list are an exact match of another list - python
[英]How do I found exact matches in python in a `for` clause with many conditions?
例如,我有這個列表:
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]。
評論:..由於區分大小寫更精確
我同意,更籠統地說,你的 const,例如["he", "boy", "him", "his"]
和words
, ["here", "we", "have"]
應該都是小寫的。
問題:你能用文字說明你在哪里寫的嗎?
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
解決方案:使用早斷。
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.