如何将diff'ed文本输出到单独的文件中? python3

问题描述 投票:0回答:1

所以我试图制作一个机器人,在比较两个文本文件(使用requests.get('url=').text方法生成)之后发送消息,只显示新行/文本/已添加/删除的任何一个。

我知道有difflib。 HtmlDiff(make_file())不适合我,因为它只是弄乱了文件。另外,根据我的理解,它只需要输出一个html文件。然后你在浏览器和Wuala中打开它!你有比较。

我尝试搜索,但找不到只输出已更改/添加的文本的库。

目前我这样做了:

def htmlCompare(prep_id=None):
while True:
    prep_url = requests.get(prep_template.format(prep_id))
    c1 = prep_url
    c2 = ''
    if c2 != c1:
        compare = difflib.HtmlDiff().make_file(fromlines=c1, tolines=c2, numlines=1)
        c2 = c1
        config_compare_save = open('compare_{}_main.txt'.format(prep_id), 'w')
        config_compare_save.write(compare)
        config_compare_save.close()
    else:  # don't mind this meaningless condition for now, I left this for something for later :)
        time.sleep(10)

但是,正如你所知,这并不能给我我需要的结果。试图使用Differ(),但看起来我不知道如何使用它。甚至不确定这是否是我首先需要使用的方法。但据我所知,这与我可能使用的最接近。

python python-3.x compare diff
1个回答
0
投票

问题:尝试使用Differ(),...从我所知道的,这是我可能必须使用的最接近的。

注意:只有..._data的第一行是相等的!

import difflib

_old_data = "refno,title,author,year,price\n\
1001,CPP,MILTON,2008,456\n\
1002,JAVA,Gilson,2002,456\n\
1003,Adobe Flex,,2010,566\n\
1004,General Knowledge,Sinson,2007,465\n\
1005,Actionscript,Gilto,2008,480\n".splitlines(keepends=False)

_new_data = "refno,title,author,year,price\n\
1001,CPP,MILTON,2010,456,2008\n\
1002,JAVA,Gilson,2002\n\
1003,Adobe Flexi,Johnson,2010,566\n\
1004,General Knowledge,Simpson,2007,465\n\
105,Action script,Gilto,2008,480\n\
2000,Drama,DayoNe,,2020,560\n".splitlines(keepends=False)

diff = difflib.Differ()

for line in diff.compare(_old_data, _new_data):
    if line.startswith(('?',' ')):
        # Skip diff control lines ?
        # Skip equal lines ' '
        pass
    else:
        #print(line[2:])
        print(line)

Qutput: - 1001,CPP,MILTON,2008,456 + 1001,CPP,MILTON,2010,456,2008 - 1002,JAVA,Gilson,2002,456 + 1002,JAVA,Gilson,2002 - 1003,Adobe Flex ,, 2010,566 + 1003,Adobe Flexi,Johnson,2010,566 - 1004,General Knowledge,Sinson,2007,465 + 1004,General Knowledge,Simpson,2007,465 - 1005,Actionscript,Gilto,2008,480 + 105,动作脚本,Gilto,2008,480 + 2000,Drama,DayoNe ,, 2020,560

用Python测试:3.4.2

© www.soinside.com 2019 - 2024. All rights reserved.