Home Backend Development Python Tutorial How to use Python regular expressions to extract ID number

How to use Python regular expressions to extract ID number

Jun 22, 2023 am 10:35 AM
python regular expression identification number

In the process of data processing, it is often necessary to extract information in a specific format from text. As a relatively common piece of personal information, ID number is often used in data processing. You can use Python regular expressions to easily extract the ID number and perform certain verification on it.

The ID number is composed of 18 digits, including the region, date of birth and verification code in the ID number. In Python, we can use the regular expression function of the re module to extract the ID number.

First, we need to prepare a text file containing the ID number. Assume that the file is named id_list.txt, and each line contains an ID number.

Next, we can use the following code to read the file and extract the ID number:

import re

# 读取文件
with open('id_list.txt', 'r') as f:
    content = f.read()

# 使用正则表达式匹配身份证号码
pattern = r'd{18}|(d{17}(d|X|x))'
id_list = re.findall(pattern, content)
Copy after login

In the above code, we used the regular expression r'd{ 18}|(d{17}(d|X|x))' to match the ID number. There are two parts in this regular expression, namely d{18} and d{17}(d|X|x). Among them, d{18} means matching 18 digits, that is, the complete ID number; d{17}(d|X|x) means matching 17 digits and the last digit The ID number may be numbers or letters X/x. By connecting the two parts using the | symbol, we can match both the complete ID number and the ID number with the verification code at the same time.

Use the re.findall function to match all strings that match the regular expression in the text and return a list of matching results. Here, we save the extracted ID number list into the id_list variable.

Next, we can verify the extracted ID number. The verification rules of ID card numbers can refer to relevant standards, which are briefly introduced here.

The check code is the last digit or letter X/x in the ID number. It is derived from the first 17 digits through a certain algorithm. The calculation method of the check code is as follows:

  1. Multiply the first 17 digits by the corresponding weight coefficients to get 17 products;
  2. Add the 17 products to get a total ;
  3. Divide the sum by 11 to get a remainder;
  4. Obtain the check code based on the remainder. The specific correspondence is as follows: when the remainder is 0, the check code is 1; when the remainder is 1 , the check code is 0;
    When the remainder is 2, the check code is X/x; when the remainder is 3-10, the check code is 11 minus the remainder.

The following is the Python code implementation of the check code:

# 校验码计算
def check_code(id_num: str) -> str:
    if len(id_num) == 18:
        factor_list = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        check_list = list(id_num[:-1])
        check_sum = sum([int(check_list[i]) * factor_list[i] for i in range(17)])
        check_num = (12 - check_sum % 11) % 11
        if check_num == 0:
            return '1'
        elif check_num == 1:
            return '0'
        elif check_num == 2:
            return 'X'
        else:
            return str(12 - check_num)
    else:
        return ''
Copy after login

In the above code, we define a function named check_code to calculate the check code of the ID card number. The parameter of the function is the ID number, and the return value is the verification code.

Finally, we can verify the extracted ID number in the loop and only retain the ID number with the correct verification code:

# 进行校验,并输出结果
valid_id_list = []
for id_num in id_list:
    # 计算校验码
    code = check_code(id_num[0])
    if code and code == id_num[0][-1]:
        valid_id_list.append(id_num[0])
print(valid_id_list)
Copy after login

In the above code, we define An empty list named valid_id_list is used to store ID numbers with correct verification codes. Use a loop to traverse all the extracted ID numbers and calculate their check codes. If the check code is the same as the check code in the extracted ID number, add the ID number to valid_id_list. Finally, we output valid_id_list to get a list of ID numbers with correct verification codes.

In general, using Python's re module and regular expressions can easily extract ID numbers from text, and it can also be verified to a certain extent. This is very helpful for processing formatted information such as ID numbers.

The above is the detailed content of How to use Python regular expressions to extract ID number. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles