博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
difflib开发对比工具
阅读量:4069 次
发布时间:2019-05-25

本文共 5940 字,大约阅读时间需要 19 分钟。

1. 简单应用

import difflibdef read_file(file):    try:        with open(file, "r", encoding="utf8") as fp:            return fp.readlines()    except IOError:        print("ERROR: 没有找到文件:%s或读取文件失败!" % file)def compare_file(file1, file2, output):    content1 = read_file(file1)    content2 = read_file(file2)        d = difflib.HtmlDiff()    result = d.make_file(content1, content2)    with open(output, 'w') as f:        f.writelines(result)if __name__=="__main__":    file1 = "file1.txt"    file2 = "file2.txt"    compare_file(file1, file2, "result.html")

在这里插入图片描述

2. 结合django框架开发对比工具

2.1 创建Django工程

在这里插入图片描述

2.2 各文件配置

app.py

from django.apps import AppConfigclass appConfig(AppConfig):    name = 'compare'

views.py

from django.shortcuts import renderimport difflibfrom bs4 import BeautifulSoupimport osimport webbrowser as webproDir = os.path.join(os.path.split(os.path.dirname(__file__))[0],"templates")#打开初始页面web.open("http://127.0.0.1:9000/compare")#定义比较文本方法def compare_file(content1, content2, result):    content1 = content1.split("\n")    content2 = content2.split("\n")    b = difflib.HtmlDiff()    r = b.make_file(fromlines=content1, tolines=content2)    sp=BeautifulSoup(r, 'lxml')    style = sp.find('style')    style.string += ".nowrap{width:50%;word-break:break-all;}"    html = sp.prettify()    html = html.replace('nowrap="nowrap"', 'class="nowrap"')        with open(result, 'w',encoding="utf8") as f:        f.writelines(html)#定义初始接口   def compare(req):    return render(req,"index.html")#定义展示比较结果接口def result(req):    body = req.POST    content1 = body.get("content1")    content2 = body.get("content2")    file_path = os.path.join(proDir, "test.html")    compare_file(content1, content2, file_path)    return render(req,"test.html")

settings.py

"""Django settings for blog_demo project.Generated by 'django-admin startproject' using Django 2.2.7.For more information on this file, seehttps://docs.djangoproject.com/en/2.2/topics/settings/For the full list of settings and their values, seehttps://docs.djangoproject.com/en/2.2/ref/settings/"""import os# Build paths inside the project like this: os.path.join(BASE_DIR, ...)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'qd_nl4f+v7@_5l1o^4zoqtnitvdn11z+++$vkky*u)t0k*iyeo'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    "compare", #新增]MIDDLEWARE = [    'django.middleware.security.SecurityMiddleware',    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.common.CommonMiddleware',#     'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.clickjacking.XFrameOptionsMiddleware',]ROOT_URLCONF = 'MyCompare.urls'TEMPLATES = [    {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': {
'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]WSGI_APPLICATION = 'MyCompare.wsgi.application'# Database# https://docs.djangoproject.com/en/2.2/ref/settings/#databasesDATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}# Password validation# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [ {
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },]# Internationalization# https://docs.djangoproject.com/en/2.2/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/2.2/howto/static-files/STATIC_URL = '/static/'

urls.py

from django.contrib import adminfrom django.urls import pathfrom compare.views import *urlpatterns = [    path('compare',compare),    path('result',result)]

wsgi.py

import osfrom django.core.wsgi import get_wsgi_applicationos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyCompare.settings')application = get_wsgi_application()

templates.index.html

Compare

manage.py

#!/usr/bin/env python"""Django's command-line utility for administrative tasks."""import osimport sysdef main():    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyCompare.settings')    try:        from django.core.management import execute_from_command_line    except ImportError as exc:        raise ImportError(            "Couldn't import Django. Are you sure it's installed and "            "available on your PYTHONPATH environment variable? Did you "            "forget to activate a virtual environment?"        ) from exc    execute_from_command_line(sys.argv)if __name__ == '__main__':    main()

startApp.py,用于启动应用

import osos.system("python manage.py runserver 9000")

2.3 测试

1.启动startApp.py

在这里插入图片描述
2.查看结果
在这里插入图片描述

转载地址:http://etmji.baihongyu.com/

你可能感兴趣的文章
为什么很多程序员都选择跳槽?
查看>>
mongdb介绍
查看>>
mongdb在java中的应用
查看>>
区块链技术让Yotta企业云盘为行政事业服务助力
查看>>
Yotta企业云盘更好的为媒体广告业服务
查看>>
Yotta企业云盘助力科技行业创高峰
查看>>
Yotta企业云盘更好地为教育行业服务
查看>>
Yotta企业云盘怎么帮助到能源化工行业
查看>>
企业云盘如何助力商业新发展
查看>>
医疗行业运用企业云盘可以带来什么样的提升
查看>>
能源化工要怎么管控核心数据
查看>>
媒体广告业如何运用云盘提升效率
查看>>
企业如何运用企业云盘进行数字化转型-实现新发展
查看>>
司法如何运用电子智能化加快现代化建设
查看>>
iSecret 1.1 正在审核中
查看>>
IOS开发的开源库
查看>>
IOS开发的开源库
查看>>
Jenkins - sonarqube 代码审查
查看>>
Jenkins + Docker + SpringCloud 微服务持续集成(一)
查看>>
Jenkins + Docker + SpringCloud 微服务持续集成 - 单机部署(二)
查看>>