开放的编程资料库

当前位置:我爱分享网 > Python教程 > 正文

Python 使用 Faker

PythonFaker教程展示了如何使用Faker包在Python中生成假数据。我们使用joke2k/faker库。

伪造者

Faker是一个生成假数据的Python库。虚假数据通常用于测试或用一些虚拟数据填充数据库。Faker深受PHP的Faker、Perl的Data::Faker和Ruby的Faker的启发。

设置Faker

该软件包随composer一起安装。

$ pip install Faker 

我们安装Faker模块。

$ pip install Dumper

此外,我们安装了Dumper,它在转储变量时提供更好的控制台输出。

Faker生成器

faker.Faker创建并初始化一个faker生成器,它可以通过访问以数据类型命名的属性来生成数据。

Faker将数据生成委托给提供者。默认提供程序使用英语语言环境。Faker支持其他语言环境;它们的完成程度不同。

简单的骗子

下面的例子是Faker的简单演示。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'name: {faker.name()}')
print(f'address: {faker.address()}')

print(f'text: {faker.text()}')

该示例输出假名、地址和文本。

$ ./simple.py
name: Arthur Patton
address: 0638 Larsen Way
Tylermouth, CA 48344
text: Save general start bar. Become class both bank Mrs so myself.
Each difficult performance even. Total anyone develop her raise research both.
Laugh sport necessary tree. As during day up fall.

这是一个示例输出。

假名

在第二个例子中,我们伪造了与用户名相关的数据。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'Name: {faker.name()}')
print(f'First name: {faker.first_name()}')
print(f'Last name: {faker.last_name()}')

print('--------------------------')

print(f'Male name: {faker.name_male()}')
print(f'Female name: {faker.name_female()}')

该示例创建了男性和女性的假全名、名字和姓氏。

$ ./names.py
Name: Tara Brown
First name: Stephanie
Last name: Martin
--------------------------
Male name: John Banks
Female name: Lacey Roberts

这是一个示例输出。

伪造工作

作业由job生成。

#!/usr/bin/python

from faker import Faker

faker = Faker()

for _ in range(6):
    print(faker.job())

该示例创建了六个假工作。

$ ./jobs.py
Town planner
Paediatric nurse
Geographical information systems officer
Water quality scientist
Engineer, maintenance
Designer, ceramics/pottery

这是一个示例输出。

伪造语言环境数据

Faker在一定程度上支持本地化数据。语言环境被传递给构造方法。注意语言环境被完成到不同的级别。

#!/usr/bin/python

from faker import Faker

faker = Faker('cz_CZ')

for i in range(3):

    name = faker.name()
    address = faker.address()
    phone = faker.phone_number()

    print(f'{name}, {address}, {phone}')

该示例生成捷克语的虚假数据。

$ ./localized.py
Irena Novotná, Nad Šancemi 725
055 80 Bojkovice, 606 136 053
Stanislav Svoboda, Březanova 225
621 17 Bystřice pod Hostýnem, 727 057 251
Klára Moravcová, Neužilova 6/3
134 97 Česká Kamenice, 606 374 469

这是一个示例输出。请注意,捷克语有口音。

伪造货币

以下示例为货币创建虚假数据。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'currency: {faker.currency()}')
print(f'currency name: {faker.currency_name()}')

print(f'currency code: {faker.currency_code()}')

该程序生成假货币。

$ ./currencies.py
currency: ('ISK', 'Icelandic króna')
currency name: Israeli new shekel
currency code: DJF

这是一个示例输出。

造词

Faker允许创建虚拟词。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'a word: {faker.word()}')
print(f'six words: {faker.words(6)}')

words = ['forest', 'blue', 'cloud', 'sky', 'wood', 'falcon']

print(f'customized unique words: {faker.words(3, words, True)}')

该示例创建虚拟词。

print(f'a word: {faker.word()}')

这一行生成一个假词。

print(f'six words: {faker.words(6)}')

这里我们生成六个虚拟词。

words = ['forest', 'blue', 'cloud', 'sky', 'wood', 'falcon']

print(f'customized unique words: {faker.words(3, words, True)}')

我们还可以从预定义的单词列表中创建假单词。

$ words.py
a word: show
six words: ['value', 'its', 'those', 'wish', 'enter', 'hold']
customized unique words: ['forest', 'blue', 'sky']

这是一个示例输出。

伪造个人资料

Faker可以使用simple_profile创建简单的虚拟配置文件,并使用profile创建扩展配置文件。

#!/usr/bin/python

from faker import Faker
import dumper

faker = Faker()

profile1 = faker.simple_profile()
dumper.dump(profile1)

print('--------------------------')

profile2 = faker.simple_profile('M')
dumper.dump(profile2)

print('--------------------------')

profile3 = faker.profile(sex='F')
dumper.dump(profile3)

该示例为男性和女性创建虚拟配置文件。

$ ./profiles.py
<dict at 0x20d590a7678>:
  username: 'gmorgan'
  name: 'Jessica Clark'
  sex: 'F'
  address: '694 Joseph Valleys\nJohnfort, ME 81780'
  mail: 'bettybuckley@yahoo.com'
  birthdate: <str at 0x20d5bcbd7b0>: 'datetime.date(1938, 9, 18)'
--------------------------
<dict at 0x20d5b0065e8>:
  username: 'mrios'
  name: 'Harold Wagner'
  sex: 'M'
  address: '26439 Robinson Radial\nWest Meghanmouth, PA 85463'
  mail: 'josechoi@gmail.com'
  birthdate: <str at 0x20d5bcbd7b0>: 'datetime.date(1986, 8, 18)'
--------------------------
<dict at 0x20d5bd24990>:
  job: 'Engineer, communications'
  company: 'Jackson-Willis'
  ssn: '430-41-6118'
  residence: 'USNS Odom\nFPO AP 47095'
  current_location: <tuple at 0x20d5bca9a88>
    0: <str at 0x20d5bd248a0>: "Decimal('74.1885785')"
    1: <str at 0x20d5bd248a0>: "Decimal('119.951995')"
  blood_group: 'O-'
  website: ['http://roberson.com/']
  username: 'ygutierrez'
  name: 'Lindsay Walker'
  sex: 'F'
  address: '22968 Beverly Road Suite 918\nTimothyborough, SD 10494'
  mail: 'aliciamccall@yahoo.com'
  birthdate: <str at 0x20d5bcbd7b0>: 'datetime.date(1979, 1, 4)'

这是一个示例输出。

伪造数字

Faker允许生成随机数字和整数。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'Random int: {faker.random_int()}')
print(f'Random int: {faker.random_int(0, 100)}')
print(f'Random digit: {faker.random_digit()}')

该示例生成随机数字和整数。

print(f'Random int: {faker.random_int(0, 100)}')

我们可以在random_int方法中指定边界。

$ ./fake_numbers.py
Random int: 5181
Random int: 91
Random digit: 9

这是一个示例输出。

伪造哈希和uuid

Faker支持虚拟哈希和uuid。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'md5: {faker.md5()}')
print(f'sha1: {faker.sha1()}')
print(f'sha256: {faker.sha256()}')
print(f'uuid4: {faker.uuid4()}')

该示例生成三个假哈希值和一个uuid值。

$ ./hash_uuid.py
md5: aace57d56794686acec9eb190d401d46
sha1: 9f8f6af3089e7b5ed571591701afcfd9c2bb7a0e
sha256: 8b117b58599809f50735c701f598312b0f64203a8ffacde09af23db69cfd62d5
uuid4: 38092dcd-0e49-4ac0-b39b-7edf6db62290

这是一个示例输出。

伪造互联网相关数据

Faker有几个用于伪造互联网相关数据的访问器。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'Email: {faker.email()}')
print(f'Safe email: {faker.safe_email()}')
print(f'Free email: {faker.free_email()}')
print(f'Company email: {faker.company_email()}')

print('------------------------------------')

print(f'Host name: {faker.hostname()}')
print(f'Domain name: {faker.domain_name()}')
print(f'Domain word: {faker.domain_word()}')
print(f'TLD: {faker.tld()}')

print('------------------------------------')

print(f'IPv4: {faker.ipv4()}')
print(f'IPv6: {faker.ipv6()}')
print(f'MAC address: {faker.mac_address()}')

print('------------------------------------')

print(f'Slug: {faker.slug()}')
print(f'Image URL: {faker.image_url()}')

该示例显示了各种互联网相关数据,包括电子邮件、域名、别名、IP地址和URL。

$ ./internet.py
Email: hescobar@acevedo.info
Safe email: jonesgregory@example.net
Free email: zchambers@yahoo.com
Company email: paulbailey@gordon-woods.com
------------------------------------
Host name: desktop-12.rodriguez-underwood.com
Domain name: henry.com
Domain word: davis
TLD: com
------------------------------------
IPv4: 192.31.48.26
IPv6: 75cd:2c43:37f5:774c:dd:5a2f:ae5d:bfc9
MAC address: 3d:b1:39:ec:c6:53
------------------------------------
Slug: of-street-fight
Image URL: https://placeimg.com/311/871/any

这是一个示例输出。

伪造日期和时间

Faker有很多伪造日期和时间值的方法。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'Date of birth: {faker.date_of_birth()}')
print(f'Century: {faker.century()}')
print(f'Year: {faker.year()}')
print(f'Month: {faker.month()}')
print(f'Month name: {faker.month_name()}')
print(f'Day of week: {faker.day_of_week()}')
print(f'Day of month: {faker.day_of_month()}')
print(f'Time zone: {faker.timezone()}')
print(f'AM/PM: {faker.am_pm()}')

第一个示例显示了针对出生日期、日期时间部分、时区和上午/下午的虚假方法。

$ date_time.py
Date of birth: 2008-08-07
Century: IV
Year: 1981
Month: 05
Month name: January
Day of week: Saturday
Day of month: 26
Time zone: Asia/Oral
AM/PM: AM

这是一个示例输出。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'Datetime this century: {faker.date_time_this_century()}')
print(f'Datetime this decade: {faker.date_time_this_decade()}')
print(f'Datetime this year: {faker.date_time_this_year()}')
print(f'Datetime this month: {faker.date_time_this_month()}')

print('-------------------------')

print(f'Date this century: {faker.date_this_century()}')
print(f'Date this decade: {faker.date_this_decade()}')
print(f'Date this year: {faker.date_this_year()}')
print(f'Date this month: {faker.date_this_month()}')

print('-------------------------')

TOTAL_SECONDS = 60*60*24*2 # two days

series = faker.time_series(start_date='-12d', end_date='now', precision=TOTAL_SECONDS)

for val in series:
    print(val[0])

第二个示例显示了生成当前世纪、十年、年份或月份的日期时间值的方法。它还包括时间序列值的生成。

$ date_time2.py
Datetime this century: 2013-08-06 23:42:47
Datetime this decade: 2010-02-15 01:08:34
Datetime this year: 2019-03-10 05:32:42
Datetime this month: 2019-04-06 10:13:53
-------------------------
Date this century: 2014-11-04
Date this decade: 2018-03-07
Date this year: 2019-02-07
Date this month: 2019-04-04
-------------------------
2019-03-26 16:16:49
2019-03-28 16:16:49
2019-03-30 16:16:49
2019-04-01 16:16:49
2019-04-03 16:16:49
2019-04-05 16:16:49

这是一个示例输出。

#!/usr/bin/python

from faker import Faker

faker = Faker()

print(f'Unix time: {faker.unix_time()}')
print(f'Datetime: {faker.date_time()}')
print(f'iso8601: {faker.iso8601()}')
print(f'Date: {faker.date()}')
print(f'Time: {faker.time()}')

print('-------------------------')

print(f"Datetime between: {faker.date_time_between(start_date='-15y', end_date='now')}")
print(f"Date between: {faker.date_between()}")

print('-------------------------')

print(f"Future datetime: {faker.future_datetime()}")
print(f"Future date: {faker.future_date()}")
print(f"Past datetime: {faker.past_datetime()}")
print(f"Past date: {faker.past_date()}")

第三个示例展示了各种日期时间格式的方法,用于获取选定范围的日期时间值,以及用于生成未来或过去的值。

$ date_time3.py
Unix time: 1389138339
Datetime: 1988-01-24 09:16:09
iso8601: 2014-04-22T04:19:18
Date: 2009-05-01
Time: 12:07:51
-------------------------
Datetime between: 2011-03-18 21:00:23
Date between: 1992-07-09
-------------------------
Future datetime: 2019-04-11 13:36:02
Future date: 2019-04-14
Past datetime: 2019-03-21 12:27:20
Past date: 2019-03-22

这是一个示例输出。

用Faker生成XML数据

在下面的示例中,我们使用Faker和Jinja2模板生成XML数据。XML文件将包含用户。

$ pip install jinja2

我们安装Jinja2模板引擎。

#!/usr/bin/python

from jinja2 import Environment, FileSystemLoader
from faker import Faker

class User:

    def __init__(self, first_name, last_name, occupation):

        self.first_name = first_name
        self.last_name = last_name
        self.occupation = occupation

faker = Faker()
users = []

for _ in range(10):

    first_name = faker.first_name()
    last_name = faker.last_name()
    occupation = faker.job()

    user = User(first_name, last_name, occupation)

    users.append(user)

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('users.xml.j2')
output = template.render(users=users)

print(output, file=open('users.xml', 'w'))

该程序会生成一个包含10个用户的列表。该列表被传递给Jinja2模板进行处理。该模板位于templates目录中。生成的内容写入users.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<users>
    {% for user in users %}
    <user id="{{ loop.index }}">
        <firstname>{{ user.first_name }}</firstname>
        <lastname>{{ user.last_name }}</lastname>
        <occupation>{{ user.occupation }}</occupation>
    </user>
    {% endfor %}
</users>

在模板中,我们使用for指令来处理用户列表。

在本教程中,我们使用PythonFaker在Python中生成假数据。

阅读Python教程或列出所有Python教程。

未经允许不得转载:我爱分享网 » Python 使用 Faker

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏