search
HomeBackend DevelopmentPython TutorialHow 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:

  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 ''

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!

Statement
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
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.