How to use Python regular expressions to extract ID 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)
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:
- Multiply the first 17 digits by the corresponding weight coefficients to get 17 products;
- Add the 17 products to get a total ;
- Divide the sum by 11 to get a remainder;
- 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 ''
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)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
