我编写了一个带有生成器表达式的if条件。
self.keyword_list = ['Buzz', 'Heard on the street', 'familiar with the development', 'familiar with the matter', 'Sources' ,'source', 'Anonymous', 'anonymity', 'Rumour', 'Scam', 'Fraud', 'In talks', 'Likely to', 'Cancel', 'May', 'Plans to', 'Raids' ,'raid', 'search', 'Delisting', 'delist', 'Block', 'Exit', 'Cheating', 'Scouts', 'scouting', 'Default', 'defaulted', 'defaulter', 'Calls off', 'Lease out', 'Pick up', 'delay', 'arrest', 'arrested', 'inks', 'in race', 'enters race', 'mull', 'consider', 'final stage', 'final deal', 'eye', 'eyes', 'probe', 'vie for', 'detects', 'allege', 'alleges', 'alleged', 'fabricated', 'inspection', 'inspected', 'to monetise', 'cancellation', 'control', 'pact', 'warning', 'IT scanner', 'Speculative', 'Divest', 'Buzz', 'Heard on the street', 'familiar with the development', 'familiar with the matter', 'Sources', 'source', 'Anonymous', 'anonymity', 'Rumour', 'Scam', 'Fraud', 'In talks', 'Likely to', 'Cancel', 'May', 'Plans to ', 'Raids', 'raid', 'search', 'Delisting', 'delist', 'Block', 'Exit', 'Cheating', 'Scouts','scouting', 'Default', 'defaulted', 'defaulter', 'Calls off', 'Lease out', 'Pick up', 'delay', 'arrest', 'arrested', 'inks', 'in race', 'enters race', 'mull', 'consider', 'final stage', 'final deal', 'eye', 'eyes', 'probe', 'vie for', 'detects', 'allege', 'alleges', 'alleged', 'fabricated', 'inspection', 'inspected', 'monetise', 'cancellation', 'control', 'pact', 'warning', 'IT scanner', 'Speculative', 'Divest']
if any(re.search(item.lower(), record['title'].lower()+' '+record['description'].lower()) for item in self.keyword_list):
#for which value of item condition became true?
#print item does not work
print record如果条件是真,那么我想打印匹配的项目名称。我怎么弄到这个?
发布于 2015-09-10 09:36:26
不要使用any(),并将生成器表达式更改为使用过滤器(将测试移至末尾),然后使用next()获得第一个匹配:
matches = (item for item in self.keyword_list if re.search(item.lower(), record['title'].lower() + ' ' + record['description'].lower()))
first_match = next(matches, None)
if first_match is not None:
print record或者您只需使用for循环并在第一次匹配之后爆发:
for item in self.keyword_list:
if re.search(item.lower(), record['title'].lower() + ' ' + record['description'].lower()):
print record
break您可以通过预先计算要匹配的正则表达式,并使用re.IGNORECASE标志来进一步清理这些变体,这样您就不必将所有内容小写:
pattern = re.compile(
'{} {}'.format(record['title'], record['description']),
flags=re.IGNORECASE)
matches = (item for item in self.keyword_list if pattern.search(item))
first_match = next(matches, None)
if first_match is not None:
print record或
pattern = re.compile(
'{} {}'.format(record['title'], record['description']),
flags=re.IGNORECASE)
for item in self.keyword_list:
if pattern.search(item):
print record
breakhttps://stackoverflow.com/questions/32498133
复制相似问题