diff, сгенерированный diff_match_patch, разделен

Я пытаюсь проанализировать различия, сгенерированные библиотекой diff_match_patch, чтобы получить простой параллельный отчет сравнения в Python, учитывая следующее дополнительное ограничение на данные:

import diff_match_patch as gdiff

sdiff = gdiff.diff_match_patch()
diff = sdiff.diff_main(src_string, tgt_string)
sdiff.diff_cleanupSemantic(diff)
  1. Входные файлы - это CSV-файлы с фиксированной длиной столбца.
  2. Данные являются столбчатыми, и меня интересует только то, что есть разница в конкретной ячейке, а не в том, какова фактическая разница внутри ячейки (на данный момент).

Вот первоначальный черновик кода, который на данный момент предполагает, что есть только вставки и удаления строк.

import diff_match_patch as gdiff
import pandas as pd
import xlsxwriter

if __name__ == "__main__":
    src = "Table1.csv"  # Old
    tgt = "Table2.csv"  # New

    try:
        with open(src, 'r', encoding="utf8") as sf:
            src_string = sf.read()
    except Exception as err:
        print("Error opening source output file {}".format(src))
        print(err)

    try:
        with open(tgt, 'r', encoding="utf8") as tf:
            tgt_string = tf.read()
    except Exception as err:
        print("Error opening target output file {}".format(tgt))
        print(err)

    table1 = pd.read_csv('Table1.csv', parse_dates=True, sep=',', header=None)
    table2 = pd.read_csv('Table2.csv', parse_dates=True, sep=',', header=None)

    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('Result.xlsx', engine='xlsxwriter')

    table1.ix[0:0].to_excel(writer,
                            sheet_name='Sheet2',
                            startrow=0,
                            startcol=0,
                            header=False)

    table2.ix[0:0].to_excel(writer,
                            sheet_name='Sheet2',
                            startrow=0,
                            startcol=10,
                            header=False)

    sdiff = gdiff.diff_match_patch()
    diff = sdiff.diff_main(src_string, tgt_string)
    sdiff.diff_cleanupSemantic(diff)

    for row in diff:
        print()
        print(row)
        print()

    dlRow = 1  # Row number of left dataframe  (#Old)
    drRow = 1  # Row number of right dataframe (#New)
    eRow = 1  # Row number in excel sheet.

    for counter, row in enumerate(diff):
        type = diff[counter][0]

        # Remove the header from the first tuple.
        if counter == 0:
            text = diff[counter][1][diff[counter][1].find('\n') + 1:]
        else:
            text = diff[counter][1]

        if type == 0 and text != '':
            matchedRows = text.count('\n')

            table1.ix[dlRow:dlRow + matchedRows - 1].to_excel(writer,
                                                              sheet_name='Sheet2',
                                                              startrow=eRow,
                                                              startcol=0,
                                                              header=False)

            table2.ix[drRow:drRow + matchedRows - 1].to_excel(writer,
                                                              sheet_name='Sheet2',
                                                              startrow=eRow,
                                                              startcol=10,
                                                              header=False)
            # Position the cursor to the next row in the dataframe.
            dlRow += matchedRows
            drRow += matchedRows

            # Position the cursor for the next row in the excel.
            eRow += matchedRows

        if type == 1 and text != '':
            insertedRows = text.count('\n')

            table2.ix[drRow:drRow + insertedRows - 1].to_excel(writer,
                                                               sheet_name='Sheet2',
                                                               startrow=eRow,
                                                               startcol=10,
                                                               header=False)

            # Position the cursor to the next row in the right dataframe.
            drRow += insertedRows

            # Position the cursor for the next row in the excel.
            eRow += insertedRows

        if type == -1 and text != '':
            deletedRows = text.count('\n')

            table1.ix[dlRow:dlRow + deletedRows - 1].to_excel(writer,
                                                              sheet_name='Sheet2',
                                                              startrow=eRow,
                                                              startcol=0,
                                                              header=False)

            # Position the cursor to the next row in the left dataframe.
            dlRow += deletedRows

            # Position the cursor for the next row in the excel.
            eRow += deletedRows

Все отлично работает для простого случая. Например, diff, сгенерированный для входных файловTable1.csv а также Table2.csv здесь, содержат (-1, '') однако, поскольку я их игнорирую, на данный момент они меня не беспокоят.

Однако в других случаях, например, здесь, различия в конце, генерируемые для вставки, не подходят для простого анализа. Вставка строки разделена на четыре различий вместо одного различий.

(-1, '')


(0, '')


(1, '0 "\nZenaida Frank,Software Engineer,New York,63,1/4/2010,"$125,25')


(0, '0 "\nZorita Serrano,Software Engineer,San Francisco,56,6/1/2012,"$115,000 "\n')

Может кто-нибудь объяснить, что вызывает разделение различий таким образом? Кроме того, есть ли способ получить правильно сформированный diff, учитывая ограничения на данные?

0 ответов

Другие вопросы по тегам