This article mainly introduces examples of the python difflib module in detail, which has certain reference value. Interested friends can refer to the classes and methods provided by the
difflib module for sequencing. Differential comparison, it can compare files and generate differential result text or differential comparison page in html format. If you need to compare directories, you can use the filecmp module.
class difflib.SequenceMatcher
This class provides methods for comparing sequence pairs of arbitrary hashable types. This method will find the largest consecutive matching sequence that does not contain 'garbage' elements.
By comparing the complexity of the algorithm, it has n square operations in the worst case due to the original Gestalt matching algorithm, and has linear efficiency in the best case.
It has automatic garbage heuristics that can treat characters that are repeated more than 1% of the fragment or repeated 200 times as garbage. This feature can be turned off by setting autojunk to false.
class difflib.Differ
This class compares the differences between text lines and produces difference results or incremental results suitable for human reading. Each of the results The representation of the parts is as follows:
##class difflib.HtmlDiff
This class can be used to create HTML tables (or contain tables html file), corresponding display on both sides or row-by-row display to compare the difference results. make_file(fromlines, tolines [, fromdesc][, todesc][, context][, numlines])make_table(fromlines, tolines [, fromdesc][, todesc][, context ][, numlines])difflib.context_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])
Generator that compares a and b (a list of strings) and returns a line of difference textExample:
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'): ... sys.stdout.write(line) *** before.py --- after.py *************** *** 1,4 **** ! bacon ! eggs ! ham guido --- 1,4 ---- ! python ! eggy ! hamster guido
difflib.get_close_matches(word, possibilities [, n][, cutoff])
Return the list of maximum matching results>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] >>> import keyword >>> get_close_matches('wheel', keyword.kwlist) ['while'] >>> get_close_matches('apple', keyword.kwlist) [] >>> get_close_matches('accept', keyword.kwlist) ['except']
difflib.ndiff(a, b[, linejunk][, charjunk])
Compare a and b (string list) and return a Differ-style difference result Example:
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> print ''.join(diff), - one ? ^ + ore ? ^ - two - three ? - + tree + emu
difflib.restore(sequence, which)
Returns a result produced by two aligned sequences>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> diff = list(diff) # materialize the generated delta into a list >>> print ''.join(restore(diff, 1)), one two three >>> print ''.join(restore(diff, 2)), ore tree emu
difflib.unified_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate ][, n][, lineterm])
Compare a and b (string list) and return a difference result in unified diff format.>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'): ... sys.stdout.write(line) --- before.py +++ after.py @@ -1,4 +1,4 @@ -bacon -eggs -ham +python +eggy +hamster guidoPractical application exampleCompare two files and then generate an HTML file showing the difference results
#coding:utf-8 ''' file:difflibeg.py date:2017/9/9 10:33 author:lockey email:lockey@123.com desc:diffle module learning and practising ''' import difflib hd = difflib.HtmlDiff() loads = '' with open('G:/python/note/day09/0907code/hostinfo/cpu.py','r') as load: loads = load.readlines() load.close() mems = '' with open('G:/python/note/day09/0907code/hostinfo/mem.py', 'r') as mem: mems = mem.readlines() mem.close() with open('htmlout.html','a+') as fo: fo.write(hd.make_file(loads,mems)) fo.close()Running results:
## Generated html file comparison results:
The above is the detailed content of Detailed explanation of python difflib module. For more information, please follow other related articles on the PHP Chinese website!

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

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