banner
李大仁博客

李大仁博客

天地虽大,但有一念向善,心存良知,虽凡夫俗子,皆可为圣贤。

Generating Chinese ID numbers using Python code

Python code for generating Chinese ID numbers. When doing web scraping with Python, it is often necessary to provide a Chinese ID number. There are various validation rules for Chinese ID numbers, so I found a reliable solution online.

import random, datetime
 
def ident_generator():
    # Province codes for the first two digits of the ID number
    sheng = ('11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '66')
 
    # Randomly select a birthdate between 7000 and 25000 days ago as the birthdate (this is just a random setting, it can be improved for specific requirements)
    birthdate = (datetime.date.today() - datetime.timedelta(days = random.randint(7000, 25000)))
 
    # Concatenate the first 17 digits of the ID number (the 3rd to 6th digits are the codes for the city and district, since China is too large, I just set them as fixed values here, it can be improved with random values for specific requirements; the 15th to 17th digits are the sequence code for birthdate, randomly selected between 100 and 199)
    ident = sheng[random.randint(0, 31)] + '0101' + birthdate.strftime("%Y%m%d") + str(random.randint(100, 199))
 
    # Coefficients for each digit in the first 17 digits, represented by a dictionary, for example, the first digit needs to be multiplied by 7, and the last digit needs to be multiplied by 2
    coe = {1: 7, 2: 9, 3: 10, 4: 5, 5: 8, 6: 4, 7: 2, 8: 1, 9: 6, 10: 3, 11:7, 12: 9, 13: 10, 14: 5, 15: 8, 16: 4, 17: 2}
    summation = 0
 
    # Calculate the sum of each digit multiplied by its corresponding coefficient in the first 17 digits
    for i in range(17):
        summation = summation + int(ident[i:i + 1]) * coe[i+1]#ident[i:i+1] uses Python slicing to get each digit
 
    # Lookup table for the remainder obtained by dividing the sum of each digit multiplied by its corresponding coefficient in the first 17 digits by 11, for example, if the remainder is 0, the 18th digit is 1
    key = {0: '1', 1: '0', 2: 'X', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'}
 
    # Concatenate to get the complete 18-digit ID number
    return ident + key[summation % 11]

ident_generator()

[Source](http://www.51testing.com/html/12/15124112-3705453.html)
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.