RainyBread7

文件变化比对

20240113.py
import os
DOCU_DIR = "Documents\\"
files = os.listdir(DOCU_DIR)
order = 0#检验查看的是第一个文件
Compare = [[], []]
Name = []
for file in files:
    fname = DOCU_DIR + file
    if os.path.isdir(fname):
        continue
    Name.append(fname)
    with open(fname, encoding='utf-8') as f:
        content = f.read().split('\n')
    for text in content:
        START = text.find('"')
        END = text.find('"', START + 1)
        if (START != -1) and (END != - 1):
            Compare[order].append(text[START + 1:END])
    order += 1
    if order == 2:
        break
#去重复
for i in [0,1]:
    Compare[i] = list(set(Compare[i]))
#黑名单
banlist = []
for i in Compare[0]:
    if i in Compare[1]:
        banlist.append(i)
A = []
B = []
#print('最终比对结果:')
for i in [0,1]:
    print('第',i,'个文件:',Name[i])
    for j in Compare[i]:
        if not j in banlist: 
            #print(j)
            if i == 0:
                A.append(j)
            else:
                B.append(j)
del Compare
#询问用户是否需要对A,B,Name进行变量交换
uncertain = True
while uncertain:
    print('待改文本:',Name[0])
    print('标准文本:',Name[1])
    getResponse = input('是这样没错吗?(Y/N)')
    if getResponse[0] == 'n':
        Name[0], Name[1] = Name[1], Name[0]
        A,B = B,A
    if getResponse[0] == 'y':
        uncertain = False
From = []
To = []
#查重
print('找不同:')
for element in A:
    similarity = []
    for j in range(len(B)):
        #对obj查看相似度
        obj = B[j]
        score = 0
        for i in element:
            if i in obj:
                score += 1
        similarity.append(score)
    #查找最高相似度的句子
    highest = -1
    num = 0
    for k in range(len(similarity)):
        if similarity[k] > highest:
            highest = similarity[k]
            num = k
    #结果
    #询问用户是否进行替换
    print('文件1中:',element,'\n与文件2中:',B[num])
    getResponse = input('是否进行替换?(Y/N)')
    if getResponse[0] == 'y':
        From.append(element)
        To.append(B[num])
        print('已记录。\n')
    else: print('不替换。\n')
#替换并生成文件
print('开始生成文件...')
fname = Name[0]
with open(fname, encoding='utf-8') as f:
    content = f.read().split('\n')
newcontent = []
for text in content:
    #对每一行内容
    for i in range(len(From)):
        text = text.replace(From[i], To[i])
    newcontent.append(text)
#把newcontent写入文件
txt = ""
for i in newcontent:
    txt += i + '\n'
txt = txt[:len(txt)-1]
with open(fname + '_REVISED.txt', 'w',encoding='utf-8') as f:
    f.write(txt)
print('完成。')