Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to install and use the Faker library in Python

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to install and use the Faker library in Python". In the daily operation, I believe many people have doubts about how to install and use the Faker library in Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to install and use the Faker library in Python". Next, please follow the editor to study!

1. Background

In the process of software requirements, development and testing, sometimes we need to use some test data. In view of this situation, we generally either use the existing system data, or need to create some data manually. Due to the variety of business system data, it is ever-changing. In the process of manually manufacturing data, it may take a lot of effort and work, which is both complicated and error-prone, for example, to construct three elements of a group of users (name, mobile phone number, ID card), to construct a batch of bank card data, or to construct a batch of address address book, etc.

At this time, people often want to be lazy and fast, and most of the test data may look like this:

Test, 1300000 000123456 Zhang San, 1310000 000123456 Li Si, 1320000 000234567 Wang Wu, 1330000 000345678

The test data includes a large number of "test XX", or random keystrokes on the keyboard, which are meaningless fake data.

Is that what you did? Frankly speaking, there was a time when the author did the same thing occasionally.

However, think about it, such test data, not only to manually tap, but also can not be fake, a waste of time, a waste of manpower, low data value.

Moreover, the manual manufacture of some data can not be guaranteed, such as UUID data, MD5, SHA encryption data and so on.

In order to help you solve this problem, more or more to provide a solution or idea, today to share with you a Python data-making tool: Faker library, which can be used to generate a variety of fake data that looks "like real".

2. Introduction and installation of Faker

2.1 what is Faker

Faker is a Python package, which is mainly used to create pseudo data. Using Faker package, you no longer need to generate data manually or handwritten random numbers, you only need to call the methods provided by Faker to complete the data generation.

Project address:

2.2 installation

It is easy to install Faker, install it using pip:

Pip install Faker

In addition to the pip installation, you can also download the compilation installation from the github address provided above.

(py3_env) ➜py3_env pip show faker Name: Faker Version: 4.1.1 Summary: Faker is a Python package that generates fake data for you. Home-page: https://github.com/joke2k/faker Author: joke2k Author-email: joke2k@gmail.com License: MIT License Location: / Users/xxx/work_env/py3_env/lib/python3.7/site-packages Requires: python-dateutil, text-unidecode Required-by:

3. Faker is commonly used

3.1 basic usage

The use of Faker is also very simple, import the class from the faker module, and then instantiate the class, you can call the method to use:

From faker import Faker fake = Faker () name = fake.name () address = fake.address () print (name) print (address) # output information Ashley Love 074 Lee Village Suite 464 Dawnborough, RI 44234

Here we have created a name and an address. Since Faker is English data by default, if we need to create data in other languages, we can use the locale parameter, for example:

From faker import Faker fake = Faker (locale='zh_CN') name = fake.name () address = fake.address () print (name) print (address) # output Information Zhang Yan 175208, Block y, Chaoyang Qiu Road, Shanghai, Hainan Province

Does it look good, but it is important to note that the address here is not the real address, but a random combination of provinces, cities, roads and so on.

Here are some common language codes:

Simplified Chinese: zh_CN

Traditional Chinese: zh_TW

American English: en_US

British English: en_GB

German: de_DE

Japanese: ja_JP

Korean: ko_KR

French: fr_FR

For example, if you change the language to traditional Chinese fake = Faker (locale='zh_TW'), the output message is:

No. 10, 9, Boxing Street, Zhihong 100

3.2 Common functions

In addition to the two functions described above, fake.name and fake.address generate names and addresses, the commonly used faker functions are divided by category with the following common methods.

1. Geographic information category

Fake.city_suffix (): city, county

Fake.country (): country

Fake.country_code (): country code

Fake.district (): zone

Fake.geo_coordinate (): geographical coordinat

Fake.latitude (): geographical coordinates (latitude)

Fake.longitude (): geographical coordinates (longitude)

Fake.postcode (): zip code

Fake.province (): province

Fake.address (): detailed address

Fake.street_address (): Street address

Fake.street_name (): Street name

Fake.street_suffix (): Street, road

2. Basic information class

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Ssn (): generate ID card number

Bs (): random company service name

Company (): random company name (long)

Company_prefix (): random company name (short)

Company_suffix (): company nature

Credit_card_expire (): random credit card expiration date

Credit_card_full (): generate complete credit card information

Credit_card_number (): credit card number

Credit_card_provider (): credit card type

Credit_card_security_code (): credit card security code

Job (): random positions

First_name_female (): female name

First_name_male (): male name

Last_name_female (): female surname

Last_name_male (): male surname

Name (): randomly generates a full name

Name_female (): male full name

Name_male (): female full name

Phone_number (): randomly generate a mobile phone number

Phonenumber_prefix (): randomly generate mobile phone number range

3. Computer fundamentals, Internet information class

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Ascii_company_email (): random ASCII company mailbox name

Ascii_email (): random ASCII mailbox:

Company_email ():

Email ():

Safe_email (): secure mailbox

4. Network basic information class

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Domain_name (): generate a domain name

Domain_word (): domain word (that is, no suffix)

Ipv4 (): random IP4 address

Ipv6 (): random IP6 address

Mac_address (): random MAC address

Tld (): URL domain suffix (.com, .net.cn, etc., excluding.)

Uri (): random URI address

Uri_extension (): URL file suffix

Uri_page (): URL file (without suffix)

Uri_path (): URL file path (does not contain file name)

Url (): random URL address

User_name (): random user name

Image_url (): random URL address

5. Browser information class

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Chrome (): randomly generate browser user_agent information for Chrome

Firefox (): randomly generate browser user_agent information for FireFox

Internet_explorer (): randomly generate browser user_agent information for IE

Opera (): randomly generate browser user_agent information for Opera

Safari (): randomly generate browser user_agent information for Safari

Linux_platform_token (): random Linux information

User_agent (): random user_agent information

6. Digital category

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Numerify (): three random digits

Random_digit (): 0-9 random number

Random_digit_not_null (): random number of 1 to 9

Random_int (): random number. Default is 09999, which can be set by setting min,max.

Random_number (): random number, parameter digits sets the number of digits generated

Pyfloat ():

The number of integer digits generated by left_digits=5 #, the number of decimal places generated by right_digits=2 #, and whether positive=True # is only positive

Pyint (): random Int number (reference random_int () parameter)

Pydecimal (): random Decimal number (reference pyfloat parameter)

7. Text, encryption class

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Pystr (): random string

Random_element (): random letter

Random_letter (): random letter

Paragraph (): randomly generate a paragraph

Paragraphs (): randomly generate multiple paragraphs

Sentence (): randomly generate a sentence

Sentences (): randomly generates multiple sentences, similar to paragraphs

Text (): randomly generate an article

Word (): randomly generated words

Words (): randomly generate multiple words, similar to paragraphs, sentences, etc.

Binary (): randomly generate binary codes

Boolean (): True/False

Language_code (): randomly generate two-bit language codes

Locale (): randomly generated language / international information

Md5 (): randomly generate MD5

Null_boolean (): NULL/True/False

Password (): randomly generate passwords. Optional parameters: length: password length; special_chars: whether special characters can be used; digits: whether it contains numbers; upper_case: whether it contains uppercase letters; lower_case: whether it contains lowercase letters.

Sha1 (): random SHA1

Sha256 (): random SHA256

Uuid4 (): random UUID

8. Time information class

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Date (): random date

Date_between (): randomly generate dates within the specified range. Parameter: start_date,end_date

Date_between_dates (): randomly generate dates within the specified range, using the same as above

Date_object (): randomly produces a random date from 1970-1-1 to a specified date.

Date_time (): randomly generated at a specified time (since January 1, 1970)

Date_time_ad (): random time from AD 1 to the present

Date_time_between (): use the same as dates

Future_date (): future date

Future_datetime (): future time

Month (): random month

Month_name (): random month

Past_date (): randomly generate past dates

Past_datetime (): randomly generate elapsed time

Time (): random 24 hours

Timedelta (): random acquisition of time difference

Time_object (): random 24 hours time, time object

Time_series (): random TimeSeries object

Timezone (): random time zone

Unix_time (): random Unix time

Year (): random year

9. Python related methods

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Profile (): randomly generate archive information

Simple_profile (): randomly generate simple archive information

Pyiterable ()

Pylist ()

Pyset ()

Pystruct ()

Pytuple ()

Pydict ()

You can use dir (fake) to see what data the Faker library can fake. Currently, Faker supports nearly 300 kinds of data, as well as its own extensions.

With these data generation functions, you can use the fake object to call different methods to generate various data.

3.3 Common data scenarios

1. Construct address book records

From faker import Faker fake = Faker (locale='zh_CN') for _ in range (5): print ('name:', fake.name (), 'mobile number:' Fake.phone_number () # output Information: name: Luo Liu Mobile number: 18674751460 name: Xue Li Mobile number: 13046558454 name: Zhai Lili Mobile number: 15254904803 name: song Xiuzhen Mobile number: 13347585045 name: Kong Guizhen Mobile number: 18258911504

2. Construct credit card data

From faker import Faker fake = Faker (locale='zh_CN') print ('Card Number:', fake.credit_card_number (card_type=None)) print (' Card Provider:', fake.credit_card_provider (card_type=None)) print ('Card Security Code:', fake.credit_card_security_code (card_type=None)) print (' Card Expire:' Fake.credit_card_expire () # output information: Card Number: 676181530350 Card Provider: Diners Club / Carte Blanche Card Security Code: 615 Card Expire: 09

3. Generate personal file information

From faker import Faker fake = Faker (locale='zh_CN') print (fake.profile ()) # output information {'job':' Art Guide, 'company':' Yi Power Media Co., Ltd., 'ssn':' 370703197807179500, 'residence':' 784064qu, 'current_location': (Decimal (' 78.3608745'), Decimal ('- 95.946407'), Block L, Dongguan Street, Jizhou, Guangxi Zhuang Autonomous region) 'blood_group': 'Bamboo,' website': ['https://www.jiewang.org/',' https://www.longsong.cn/', 'https://jingyong.net/',' https://58.cn/'], 'username':' qinqiang', 'name':' Tang Wei, 'sex':' Franch, 'address':' 875743', Block a, Dongli Lhasa Street, Jianhua City, Xinjiang Uygur Autonomous region 'mail': 'shenyang@hotmail.com',' birthdate': datetime.date (2014, 4, 27)}

4. Generate Python related structure information

From faker import Faker fake = Faker (locale='zh_CN') print ('generate Python dictionary: {}' .format (fake.pydict (nb_elements=10, variable_nb_elements=True)) # Python dictionary print ('generate Python iterable object: {}.' .format (fake.pyiterable (nb_elements=10)) (variable_nb_elements=True)) # Python iterable object print ('generate Python structure: {}' .format (fake.pystruct (count=1) # Python structure # output information into Python dictionary: {'forum': 'nVcSbHlrcrhIBtwByVUM',' direct': 'drkyFUNcNxdbwYKhRLEZ',' success': 'https://fang.cn/main/search/blog/search/',' none': datetime.datetime (2006, 2, 24, 15, 40, 14) 'cause': 404, 'author': 'OTJjsFHQklpUvTPtLCqP'} generate Python iterable objects: {1088,' ignqbohwYRxqolLEzSti', 'http://gang.cn/main/search.php',' zRnNYdIpPXUxEVISHbvS', 'ToZxuBetghvlPHUumAvi', 9830,' OYAjoKeVNGhHMLgnYUAw', 970446.888,-17681479853.4069,872236250787063.0, datetime.datetime (2017, 12, 24, 5, 58, 58), 'aRSfxiUSuMqHXvKCCkMJ'} generate Python structure: ([' cKwOvdCEFOhCERMSMXSf'] {'only': 'hhwGCmjkHMOUjBTDztXp'}, {' and 'and': {0: 'vjcNqpnRbNUUxXpgVyvh', 1: [8725, 7125,' aTSJssAJUKpuRLcbiwyK'], 2: {0: 'RmWlFQQpVZIQkxZPfJnq', 1:' efsUVLgeStXbCOJDuJCf', 2: ['FgZQLCRjUTmEbBdDMEPZ',' https://min.cn/search/faq/']}}})

4. Custom Faker data type

If this data is not enough to generate data, Faker also supports the creation of custom Provider generated data.

From faker import Faker from faker.providers import BaseProvider # create a custom Provider class CustomProvider (BaseProvider): def customize_type (self): return 'test_Faker_customize_type' # add Provider fake = Faker () fake.add_provider (CustomProvider) print (fake.customize_type ())

Is it very simple? the commonly used data in the future can be created by themselves and Provider can be generated by automatic methods, which not only saves time, but also increases reusability.

At this point, the study on "how to install and use the Faker library in Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report