在 Faker 中使用名字和姓氏生成电子邮件地址 python

Generating email address using first name and last name in Faker python

我正在尝试生成一个包含人员数据的 pandas 数据集。我正在使用 Python 的 Faker 库。有没有办法使用名字和姓氏生成有效的电子邮件地址?

import pandas as pd
import numpy as np
import os
import random
from faker import Faker

def faker_categorical(num=1, seed=None):
    np.random.seed(seed)
    fake.seed_instance(seed)
    output = []
    for x in range(num):
      gender = np.random.choice(["M", "F"], p=[0.5, 0.5])
      output.append(
        {
            "First name": fake.first_name_male() if gender=="M" else  
                                                 fake.first_name_female(),
            "Last name": fake.last_name(),
            "E-mail": fake.ascii_email(),  
        })
    return output

您可以使用 Faker 的 domain_name 方法和字符串格式以及已生成的值:

first_name = fake.first_name_male() if gender =="M" else fake.first_name_female()
last_name = fake.last_name()

output.append(
    {
     "First name": first_name,
     "Last Name": last_name,
     "E-mail": f"{first_name}.{last_name}@{fake.domain_name()}"
    }
)

在更完整的方法中,您可以将 factoryboy 添加到组合中:

from factory import DictFactory, LazyAttribute
from factory.fuzzy import FuzzyChoice
from factory import Faker

class PersonDataFactory(DictFactory):

    first = LazyAttribute(lambda obj: fake.first_name_male() if obj._gender == "M" else fake.first_name_female())
    last = Faker("last_name")
    email = LazyAttribute(lambda obj: f"{obj.first}.{obj.last}@{fake.domain_name()}")
    _gender = FuzzyChoice(("M", "F"))

    class Meta:
        exclude = ("_gender",)
        rename = {"first": "First Name", "last": "Last Name", "email": "E-mail"}


PersonDataFactory()

这将导致如下结果:

{'First Name': 'Albert',
 'Last Name': 'Martinez',
 'E-mail': 'Albert.Martinez@wheeler.com'}