1. 简单应用
import difflib
def 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 AppConfig
class appConfig(AppConfig):
name = 'compare'
views.py
from django.shortcuts import render
import difflib
from bs4 import BeautifulSoup
import os
import webbrowser as web
proDir = 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, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://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 = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_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/#databases
DATABASES = {
'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-validators
AUTH_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 = True
USE_L10N = True
USE_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 admin
from django.urls import path
from compare.views import *
urlpatterns = [
path('compare',compare),
path('result',result)
]
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyCompare.settings')
application = get_wsgi_application()
templates.index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Compare</title>
<style type="text/css">
body{
margin: 5px;
}
#tabBody{
border: 1;
height:100%;
width:100%;
}
#textTargetBody1 {
border: 1;
box-sizing: border-box;
width:48%;
float:left;
}
#textTargetBody2 {
border: 1;
box-sizing: border-box;
width:48%;
}
textarea{
margin: 10px;
min-width: 300px;
width: 100%;
min-height: 800px;
height: 100%;
}
</style>
</head>
<body>
<form action="/result" method="post">
<div style="text-align:center">
<input type="submit" value="对比">
<input type="reset" value="清空">
</div>
<div id="tabBody">
<textarea class="target-body" id="textTargetBody1" name="content1"></textarea>
<textarea class="target-body" id="textTargetBody2" name="content2"></textarea>
</div>
</form>
</body>
</body>
</html>
manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def 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 os
os.system("python manage.py runserver 9000")
2.3 测试
1.启动startApp.py
2.查看结果