在Python中搜索包含特定正则表达式的特定字符串的Python

2024-09-30 20:17:57 发布

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

我是Python新手。我有一个字符串包含许多电子邮件ID和普通单词。我想得到包含特定单词的电子邮件ID的数量。目前我正在使用正则表达式来过滤包含字符串的单词,并在此列表中使用另一个正则表达式来过滤电子邮件ID。只是想知道有没有更好的方法来做这个!在

示例:

第一部分:这个fet@dmail.com是一根与…有关的线get@dmail.com以及net@dfet.com。在

Str2:场效应晶体管

程序应返回计数为2 1fet@dmail.com 2net@dfet.com在

这是我当前使用的代码。。我正在创建一个包含str2的字符串列表,并验证它是否是电子邮件id。。。在

text_to_search = ".*(" + word_to_be_searched.lower() + ").*"
regex = re.compile(text_to_search)
lister = [m.group(0) for l in row_value[column_index].lower().split( ) for m in       [regex.search(l)] if m]

for li in lister:
    if re.match("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", li):
        match_count = match_count + 1

Tags: to字符串textincomid列表for
1条回答
网友
1楼 · 发布于 2024-09-30 20:17:57

请运行下面的代码。它将解决您的问题

import re
regex = re.compile(("([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`"
"{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|"
"\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"))
email_iter = (email[0] for email in re.findall(regex, str1) if not   email[0].startswith('//'))
email_collec = []
for email in email_iter:
   email_collec.append(email)
count = 0
str2 = "fet"
for i in range(len(coll)):
    if str2 in coll[i]:
        count+=1
print count  

相关问题 更多 >