简体   繁体   English

返回所有值包含python中字典中的特定文本

[英]Return all values contains a specific text from a dictionary in python

How to return all values contains a specific text/string from a list as a comma separate value? 如何返回所有值包含列表中的特定文本/字符串作为逗号分隔值?

i have a list of emails like this: 我有一个这样的电子邮件列表:

emails = ['email@example.com',
'email1@example.com',
'email2@example.com',
'emaila@emailexample.com',
'emailb@emailexample.com',
'email33@examplex.com',
'emailas44@exampley.com',
'emailoi45@exampley.com',
'emailgh@exampley.com']

what i want to do is get all emails from the same domain like this: 我想要做的是从同一个域获取所有电子邮件,如下所示:

Website = 'example.com'
Email = 'email@example.com','email1@example.com','email2@example.com'

and so on.... 等等....

i tried this so far but can not figure out how can i achieve this, would be great if anyone help me, thanks in advance. 我到目前为止尝试了这个但是无法弄清楚我怎样才能实现这一目标,如果有人帮助我会很好,在此先感谢。

def Email(values, search):
    for i in values:
        if search in i:
            return i
    return None

data = Email(emails, 'example.com')
print(data)

You never needed a regex. 你永远不需要正则表达式。 Use a list-comprehension taking advantage of str.endswith() to look for strings with matching characters towards the end: 使用list-comprehension利用str.endswith()来查找末尾匹配字符的字符串:

emails = ['email@example.com',
          'email1@example.com',
          'email2@example.com',
          'emaila@emailexample.com',
          'emailb@emailexample.com',
          'email33@examplex.com',
          'emailas44@exampley.com',
          'emailoi45@exampley.com',
          'emailgh@exampley.com'] 
Website = 'example.com'

print([email for email in emails if email.endswith(f'@{Website}')])
# ['email@example.com', 'email1@example.com', 'email2@example.com']

You are returning value at the first iteration itself that's why you are not able to achieve the result. 您在第一次迭代时返回值,这就是您无法实现结果的原因。 You can store the emails in a list and then return the comma separated values. 您可以将电子邮件存储在list ,然后返回逗号分隔值。

Modifying your approach: 修改你的方法:

def Email(values, search):
    x = list()
    for i in values:
        if i.endswith("@" + search):
             x.append(i)
    return ", ".join(x) # Returning list as a comma separated value

emails = ["email@example.com","email1@example.com","email2@example.com","emaila@emailexample.com","emailb@emailexample.com","email33@examplex.com","emailas44@exampley.com","emailoi45@exampley.com","emailgh@exampley.com"]
website = 'example.com'

data = Email(emails, website)
print("Website = " + website)
print("Email = " + data)

Hope this answers your question!!! 希望这能回答你的问题!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM