使用 Python 的第三方库 Faker 快速生成测试数据

在编写代码时,通常需要大量测试数据。手动创建这些数据既费时又费力,不够科学。幸运的是,我们可以利用 Python 的第三方库 Faker,轻松伪造各种测试数据。Faker 提供了自动生成各种测试数据的功能,使得数据生成变得事半功倍。

安装faker

pip install Faker

基本使用

<code>from faker import Faker</code><code>fake = Faker(locale='zh_CN')<em>#语言设置为中文</em></code><code>name = fake.name()<em>#随机生成名字</em></code>

1. date_time 时间日期类:日期、年、月等    

<code>fake.date_time(tzinfo=None) <em># 随机日期时间</em></code><code>fake.iso8601(tzinfo=None) <em># 以iso8601标准输出的日期</em></code><code>fake.date_time_this_month(before_now=True, after_now=False, tzinfo=None) <em># 本月的某个日期</em></code><code>fake.date_time_this_year(before_now=True, after_now=False, tzinfo=None) <em># 本年的某个日期</em></code><code>fake.date_time_this_decade(before_now=True, after_now=False, tzinfo=None) <em># 本年代内的一个日期</em></code><code>fake.date_time_this_century(before_now=True, after_now=False, tzinfo=None) <em># 本世纪一个日期</em></code><code>fake.date_time_between(start_date="-30y", end_date="now", tzinfo=None) <em># 两个时间间的一个随机时间</em></code><code>fake.timezone() <em># 时区</em></code><code>fake.time(pattern="%H:%M:%S") <em># 时间(可自定义格式)</em></code><code>fake.am_pm() <em># 随机上午下午</em></code><code>fake.month() <em># 随机月份</em></code><code>fake.month_name() <em># 随机月份名字</em></code><code>fake.year() <em># 随机年</em></code><code>fake.day_of_week() <em># 随机星期几</em></code><code>fake.day_of_month() <em># 随机月中某一天</em></code><code>fake.time_delta() <em># 随机时间延迟</em></code><code>fake.date_object() <em># 随机日期对象</em></code><code>fake.time_object() <em># 随机时间对象</em></code><code>fake.unix_time() <em># 随机unix时间(时间戳)</em></code><code>fake.date(pattern="%Y-%m-%d") <em># 随机日期(可自定义格式)</em></code><code>fake.date_time_ad(tzinfo=None) <em># 公元后随机日期</em></code>

2. address 地址:省份、城市、区县、详细地址

<code>fake.country() <em># 国家</em></code><code>fake.city() <em># 城市</em></code><code>fake.city_suffix() <em># 城市的后缀,中文是:市或县</em></code><code>fake.address() <em># 地址</em></code><code>fake.street_address() <em># 街道</em></code><code>fake.street_name() <em># 街道名</em></code><code>fake.postcode() <em># 邮编</em></code><code>fake.latitude() <em># 维度</em></code><code>fake.longitude() <em># 经度</em></code><br>3. person 人物:性别、姓名等    
<code>fake.name() <em># 姓名</em></code><code>fake.last_name() <em># 姓</em></code><code>fake.first_name() <em># 名</em></code><code>fake.name_male() <em># 男性姓名</em></code><code>fake.last_name_male() <em># 男性姓</em></code><code>fake.first_name_male() <em># 男性名</em></code><code>fake.name_female() <em># 女性姓名</em></code>

4. file 文件:文件名、文件类型、文件扩展名等    

<code>fake.file_name(category="image", extension="png") <em># 文件名(指定文件类型和后缀名)</em></code><code>fake.file_name() <em># 随机生成各类型文件</em></code><code>fake.file_extension(category=None) <em># 文件后缀</em></code><code>fake.mime_type(category=None) <em># mime-type</em></code>

5. color 颜色

<code>fake.hex_color() <em># 16进制表示的颜色</em></code><code>fake.rgb_css_color() <em># css用的rgb色</em></code><code>fake.rgb_color() <em># 表示rgb色的字符串</em></code><code>fake.color_name() <em># 颜色名字</em></code><code>fake.safe_hex_color() <em>#安全16进制色</em></code><code>fake.safe_color_name() <em># 安全颜色名字</em></code>

6. internet 互联网

<code>fake.ipv4(network=False) <em># ipv4地址</em>fake.ipv6(network=False) <em># ipv6地址</em>fake.uri_path(deep=None) <em># uri路径</em>fake.uri_extension() <em># uri扩展名</em>fake.uri() <em># uri</em>fake.url() <em># 生成地址</em>fake.image_url(width=None, height=None) <em># 图片url</em>fake.domain_word() <em># 域名主体</em>fake.domain_name() <em># 域名</em>fake.tld() <em># 域名后缀</em>fake.user_name() <em># 用户名</em>fake.user_agent() <em># UA</em>fake.mac_address() <em># MAC地址</em>fake.safe_email() <em># 安全邮箱</em>fake.free_email() <em># 免费邮箱</em>fake.company_email() <em># 公司邮箱</em>fake.email() <em># 邮箱</em></code>

7. credit_card 银行卡:卡号、有效期、类型等

<code>fake.credit_card_number(card_type=None) <em># 卡号</em></code><code>fake.credit_card_provider(card_type=None) <em># 卡的提供者</em></code><code>fake.credit_card_security_code(card_type=None)<em># 卡的安全密码</em></code><code>fake.credit_card_expire() <em># 卡的有效期</em></code><code>fake.credit_card_full(card_type=None) <em># 完整卡信息</em></code>

8.生成python类数据

<code>fake.pybool() <em>#生成布尔类型</em></code><code>'pybool', 'pydecimal', 'pydict', 'pyfloat', 'pyint', 'pyiterable', 'pylist', 'pyset', 'pystr', 'pystr_format', 'pystruct', 'py</code><code>timezone', 'pytuple'</code>

9.生成随机类型

<code>fake.random() <em>#随机生成</em></code><code>'random', 'random_choices', 'random_digit', 'random_digit_not_null', 'random_digit_not_null_or_empty', 'random_digit_or_empty', 'random_element', 'random_elements', 'random_int', 'random_letter', 'random_lett</code><code>ers', 'random_lowercase_letter', 'random_number', 'random_sample', 'random_uppercase_letter', 'randomize_nb_elements',</code>

10. 其他随机生成

<code>fake.text(max_nb_chars=200) <em># 随机生成一篇文章</em></code><code>fake.word() <em># 随机单词</em></code><code>fake.words(nb=3) <em># 随机生成几个字</em></code><code>fake.sentence(nb_words=6, variable_nb_words=True) <em># 随机生成一个句子</em></code><code>fake.sentences(nb=3) <em># 随机生成几个句子</em></code><code>fake.paragraph(nb_sentences=3, variable_nb_sentences=True) <em># 随机生成一段文字(字符串)</em></code><code>fake.paragraphs(nb=3) <em># 随机生成成几段文字(列表)</em></code><code>fake.barcode() <em>#生成条码</em></code><code>fake.uuid4() <em>#生成uuid</em></code><code>fake.company() <em># 公司名</em></code><code>fake.company_suffix() <em># 公司名后缀</em></code><code>fake.job()<em>#工作职位 </em></code><code>fake.phone_number() <em># 手机号码</em></code><code>fake.phonenumber_prefix() <em># 手机号码前三位</em></code><code>fake.ssn() <em># 社会安全码</em></code><code>fake.user_agent() <em>#用户代理</em></code><br>fake能随机生成的所有方法汇总
<code>['__annotations__', '__class__', '__deepcopy__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subcla</code><code>ss__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_factories', '_factory_map', '_lo</code><code>cales', '_map_provider_method', '_select_factory', '_select_factory_choice', '_select_factory_distribution', '_unique_proxy', '_weights', 'aba', 'add_provider', 'address', 'administrative_unit', 'am_pm', 'android_platform_token', </code><code>'ascii_company_email', 'ascii_email', 'ascii_free_email', 'ascii_safe_email', 'bank_country', 'bban', 'binary', 'boolean', 'bothify', 'bs', 'building_number', 'cache_pattern', 'catch_phrase', 'century', 'chrome', 'city', 'city_nam</code><code>e', 'city_suffix', 'color', 'color_name', 'company', 'company_email', 'company_prefix', 'company_suffix', 'coordinate', 'country', 'country_calling_code', 'country_code', 'credit_card_expire', 'credit_card_full', 'credit_card_numb</code><code>er', 'credit_card_provider', 'credit_card_security_code', 'cryptocurrency', 'cryptocurrency_code', 'cryptocurrency_name', 'csv', 'currency', 'currency_code', 'currency_name', 'currency_symbol', 'current_country', 'current_country_</code><code>code', 'date', 'date_between', 'date_between_dates', 'date_object', 'date_of_birth', 'date_this_century', 'date_this_decade', 'date_this_month', 'date_this_year', 'date_time', 'date_time_ad', 'date_time_between', 'date_time_betwee</code><code>n_dates', 'date_time_this_century', 'date_time_this_decade', 'date_time_this_month', 'date_time_this_year', 'day_of_month', 'day_of_week', 'del_arguments', 'dga', 'district', 'domain_name', 'domain_word', 'dsv', 'ean', 'ean13', 'e</code><code>an8', 'email', 'emoji', 'enum', 'factories', 'file_extension', 'file_name', 'file_path', 'firefox', 'first_name', 'first_name_female', 'first_name_male', 'first_name_nonbinary', 'first_romanized_name', 'fixed_width', 'format', 'fr</code><code>ee_email', 'free_email_domain', 'future_date', 'future_datetime', 'generator_attrs', 'get_arguments', 'get_formatter', 'get_providers', 'hex_color', 'hexify', 'hostname', 'http_method', 'iana_id', 'iban', 'image', 'image_url', 'in</code><code>ternet_explorer', 'ios_platform_token', 'ipv4', 'ipv4_network_class', 'ipv4_private', 'ipv4_public', 'ipv6', 'isbn10', 'isbn13', 'iso8601', 'items', 'job', 'json', 'json_bytes', 'language_code', 'language_name', 'last_name', 'last</code><code>_name_female', 'last_name_male', 'last_name_nonbinary', 'last_romanized_name', 'latitude', 'latlng', 'lexify', 'license_plate', 'linux_platform_token', 'linux_processor', 'local_latlng', 'locale', 'locales', 'localized_ean', 'loca</code><code>lized_ean13', 'localized_ean8', 'location_on_land', 'longitude', 'mac_address', 'mac_platform_token', 'mac_processor', 'md5', 'mime_type', 'month', 'month_name', 'msisdn', 'name', 'name_female', 'name_male', 'name_nonbinary', 'nic</code><code>_handle', 'nic_handles', 'null_boolean', 'numerify', 'opera', 'paragraph', 'paragraphs', 'parse', 'password', 'past_date', 'past_datetime', 'phone_number', 'phonenumber_prefix', 'port_number', 'postcode', 'prefix', 'prefix_female'</code><code>, 'prefix_male', 'prefix_nonbinary', 'pricetag', 'profile', 'provider', 'providers', 'province', 'psv', 'pybool', 'pydecimal', 'pydict', 'pyfloat', 'pyint', 'pyiterable', 'pylist', 'pyset', 'pystr', 'pystr_format', 'pystruct', 'py</code><code>timezone', 'pytuple', 'random', 'random_choices', 'random_digit', 'random_digit_not_null', 'random_digit_not_null_or_empty', 'random_digit_or_empty', 'random_element', 'random_elements', 'random_int', 'random_letter', 'random_lett</code><code>ers', 'random_lowercase_letter', 'random_number', 'random_sample', 'random_uppercase_letter', 'randomize_nb_elements', 'rgb_color', 'rgb_css_color', 'ripe_id', 'romanized_name', 'safari', 'safe_color_name', 'safe_domain_name', 'sa</code><code>fe_email', 'safe_hex_color', 'sbn9', 'seed', 'seed_instance', 'seed_locale', 'sentence', 'sentences', 'set_arguments', 'set_formatter', 'sha1', 'sha256', 'simple_profile', 'slug', 'ssn', 'street_address', 'street_name', 'street_su</code><code>ffix', 'suffix', 'suffix_female', 'suffix_male', 'suffix_nonbinary', 'swift', 'swift11', 'swift8', 'tar', 'text', 'texts', 'time', 'time_delta', 'time_object', 'time_series', 'timezone', 'tld', 'tsv', 'unique', 'unix_device', 'uni</code><code>x_partition', 'unix_time', 'upc_a', 'upc_e', 'uri', 'uri_extension', 'uri_page', 'uri_path', 'url', 'user_agent', 'user_name', 'uuid4', 'weights', 'windows_platform_token', 'word', 'words', 'year', 'zip']</code><strong>实战:模拟生成1万条数据存储至excel</strong><br>也可以生成csv、json文件数据
<code>from faker import Faker</code><code>import pandas as pd</code><code><br></code><code>fake = Faker(["zh_CN"])</code><code>Faker.seed(0)</code><code><br></code><code><br></code><code>def get_data():</code><code> key_list = ["姓名", "详细地址", "所在省份", "手机号", "身份证号", "出生年月", "邮箱"]</code><code> name = fake.name()</code><code> address = fake.address()</code><code> province = address[:3]</code><code> number = fake.phone_number()</code><code> id_card = fake.ssn()</code><code> birth_date = id_card[6:14]</code><code> email = fake.email()</code><code> info_list = [name, address, province, number, id_card, birth_date, email]</code><code> person_info = dict(zip(key_list, info_list))</code><code> return person_info</code><code><br></code><code><br></code><code>df = pd.DataFrame(columns=["姓名", "详细地址", "所在省份", "手机号", "身份证号", "出生年月", "邮箱"])</code><code>for i in range(10000):</code><code> person_info = [get_data()]</code><code> df1 = pd.DataFrame(person_info)</code><code> df = pd.concat([df, df1])</code><code>df.to_excel("模拟数据.xlsx", index=None</code>

结果如下图:

图片[1]-使用 Python 的第三方库 Faker 快速生成测试数据-山海云端论坛
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容