[Python 3.x を使用] 2 つの列を持つ CSV ファイルを作成しようとしています。1 つは偽の電子メール アドレスを含み、2 番目の列にはそれぞれの関数で指定された特定の国コードを含める必要があります。
私は、国コードが - 少なくとも - 各電子メール アドレスに割り当てられて一様に配布されることを望みます。でも、一様に分散しない方法もあればいいのに。たとえば、ある国を電子メール アドレスの 30% に割り当て、別の国を 10% に割り当てることができます。
私の最大の苦労は、キーが電子メール アドレスで、値が国コードである辞書を作成し、長さが等しくなく、空の値 (None) を持たない 2 つのリストを圧縮することです。余談ですが、辞書を作成するのが最善の方法だと思いましたが、私はプログラミングとPythonに非常に慣れていないため、より良い解決策があれば共有してください!!
これは私のコードです:
from random import choice, randint
from string import ascii_lowercase
from itertools import zip_longest
import csv
def gen_name(length):
""""Generates a random name with the given amount of characters."""
return ''.join(choice(ascii_lowercase) for i in range(length))
def email_gen():
"""Generates a fake email address."""
user = gen_name(randint(5, 10))
host = gen_name(randint(5, 15))
return user + "@" + host + ".com"
def gen_plain_email_list(n):
"""Generates a list of n amount of random e-mail addresses"""
emaillist = []
for i in range(n):
emaillist.append(email_gen())
return emaillist
def gen_email_dict(n):
"""Generates a dictionary where the key is an e-mail address and the value a random country code."""
email_list = []
cc = ['us', 'gb', 'de', 'fr', 'it', 'nl', 'es', 'ae', 'br', 'au']
# Creating a list of n amount of e-mail addresses
for i in range(n):
email_list.append(email_gen())
# Creates dictionary with with an e-mail address from email_list and
# a random country code from the cc list
email_dict = dict(zip_longest(email_list, cc, fillvalue=choice(cc)))
return email_dict
def dict_to_csv(filename, n):
with open(filename, 'w', newline='') as f:
w = csv.writer(f)
w.writerows(gen_email_dict(n).items())
dict_to_csv('test.csv', 1000)
助けてくれてありがとう!