python-2.7 - 将 diff 与漂亮的 soup 对象一起使用

标签 python-2.7 beautifulsoup difflib

我正在尝试比较两个 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

关于python-2.7 - 将 diff 与漂亮的 soup 对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35704516/

相关文章:

python - 进程在 urllib2 套接字重置时挂起

python - 在 Pandas 中转换日期时间列的快速方法

python - 在 SLES 11 上安装 Python 2.7

python - 从 mac 地址转换为十六进制字符串,反之亦然 - python 2 和 3

python - BeautifulSoup 和 Python 删除 HTML 标签

python - Beautifulsoup 显示重复项

python - 有人可以解释 DiffLib 库吗?

python - 在 Python 中重新排列解析的 HTML 数据

python - 表示文本中后续更改并使用 Python 使用此表示的标准方法是什么?

python-3.x - 通过最接近的匹配合并不同长度的两列上的两个 Dataframe