对漂亮的汤对象使用 diff

Using diff with beautiful soup objects

我正在尝试比较两个 XML 文件中特定标记的所有实例的文本。我正在使用的 OCR 引擎输出一个 xml 文件,其中包含标签 <OCRCharacters>...</OCRCharacters> 中的所有 ocr 字符。

我正在使用 python 2.7.11 和 beautiful soup 4 (bs4)。在终端上,我使用两个 xml 文件名作为参数调用我的 python 程序。

我想提取每个文件的<OCRCharacters>标签中的所有字符串,用difflib逐行比较它们,并将差异写入一个新文件。

我使用 $ python parse_xml_file.py file1.xml file2.xml 从终端调用程序。

下面的代码打开每个文件并打印标签 <OCRCharacters> 中的每个字符串。我应该如何将用 bs4 制作的对象转换为我可以与 difflib 一起使用的字符串。我愿意接受更好的方法(使用 python)来做到这一点。

import sys

with open(sys.argv[1], "r") as f1:
    xml_doc_1 = f1.read()

with open(sys.argv[2], "r") as f2:
    xml_doc_2 = f2.read()

from bs4 import BeautifulSoup
soup1 = BeautifulSoup(xml_doc_1, 'xml')
soup2 = BeautifulSoup(xml_doc_2, 'xml')

print("#####################",sys.argv[1],"#####################")
for tag in soup1.find_all('OCRCharacters'):
    print(repr(tag.string))
    temp1 = repr(tag.string)
    print(temp1)
print("#####################",sys.argv[2],"#####################")    
for tag in soup2.find_all('OCRCharacters'):
    print(repr(tag.string))
    temp2 = repr(tag.string)

你可以试试这个:

import sys
import difflib
from bs4 import BeautifulSoup

text = [[],[]]
files = []
soups = []

for i, arg in enumerate(sys.argv[1:]):
  files.append(open(arg, "r").read())
  soups.append(BeautifulSoup(files[i], 'xml'))

  for tag_text in soups[i].find_all('OCRCharacters'):
    text[i].append(''.join(tag_text))

for first_string, second_string in zip(text[0], text[1]):
    d = difflib.Differ()
    diff = d.compare(first_string.splitlines(), second_string.splitlines())
    print '\n'.join(diff)

与 xml1.xml :

<node>
  <OCRCharacters>text1_1</OCRCharacters>
  <OCRCharacters>text1_2</OCRCharacters>
  <OCRCharacters>Same Value</OCRCharacters>
</node>

和xml2.xml:

<node>
  <OCRCharacters>text2_1</OCRCharacters>
  <OCRCharacters>text2_2</OCRCharacters>
  <OCRCharacters>Same Value</OCRCharacters>
</node>

输出将是:

- text1_1
?     ^

+ text2_1
?     ^

- text1_2
?     ^

+ text2_2
?     ^

  Same Value