IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]3.3.6 使用difflib.context_diff函数

    caimouse发表于 2015-09-28 11:28:33
    love 0

    只想简单地比较一下文本之间是否有变化,就可以函数defflib.context_diff来实现。

    例子:

    #python3.4.3
    
    import difflib
    
    text1 = '''  1. Beautiful is better than ugly.
       2. Explicit is better than implicit.
       3. Simple is better than complex.
       4. Complex is better than complicated.
     '''.splitlines(keepends=True)
    
    text2 = '''  1. Beautiful is better than ugly.
       3.   Simple is better than complex.
       4. Complicated is better than complex.
       5. Flat is better than nested.
       0. test
     '''.splitlines(keepends=True)
    
    for line in difflib.context_diff(text1, text2, 'fromfile', 'tofile',
                                     'fromfiledate', 'tofiledate', 1, '\n'):
        print(line)
    
    

    结果输出如下:

    *** fromfile fromfiledate

     

    --- tofile tofiledate

     

    ***************

     

    *** 1,5 ****

     

        1. Beautiful is better than ugly.

     

    !    2. Explicit is better than implicit.

     

    !    3. Simple is better than complex.

     

    !    4. Complex is better than complicated.

     

       

    --- 1,6 ----

     

        1. Beautiful is better than ugly.

     

    !    3.   Simple is better than complex.

     

    !    4. Complicated is better than complex.

     

    !    5. Flat is better than nested.

     

    !    0. test

     

    在每行头有!的,就表示此行已经作出改变。

     

    蔡军生 微信号:shenzhencai  深圳


沪ICP备19023445号-2号
友情链接