【问题标题】:reportlab sometimes adds an extra spaces between wordsreportlab 有时会在单词之间添加额外的空格
【发布时间】:2022-08-03 05:18:15
【问题描述】:

我正在使用 Google Document AI 来处理 pdf 文档。发送 pdf 文档后,Google 会发送一个 json 回复,其中包含检测到的文本和每个单词的确切位置。这是一个示例 json 响应:Screenshot of json response

{
    \"uri\": \"\",
    \"mimeType\": \"application/pdf\",
    \"text\": \"Suppose that life is absurd for the reasons that Camus claims. If that were the case, do you\\nthink Camus\'s response is 
    appropriate? If you agree with Camus, discuss at least one\\nobjection to his proposed response and reply to it. If you do not 
    agree, say why, and briefly\\ndescribe what you think might be a more fitting response.\\nIn the midst of all chaos in the world, no 

我们看到感兴趣的部分(\"In the midst\")在每个单词之间包含一个空格。

现在使用这个 json 响应,我尝试在文档上的确切位置写下每个单词,以使扫描的 pdf 可搜索。但是在某些位置,当我 Ctrl + F 文档时,我需要在单词之间添加 2 个空格。因此,我需要查找\"In the midst\",而不是查询\"In the midst\"

Single space query

Double space query

我传入要写入的令牌不包含任何空格。我写的是 \"In\" 而不是 \"In\" 或 \"In\"

这是负责编写代码的代码的样子:

for i in range(len(a)): # Loop through pages
  for j in range(len(a[i])): # Loop through words in page
    token = a[i][j]
    can.drawString(token[\"x\"], token[\"y\"], token[\"text\"])

其中 token 保存要写入的单词的数据。

记号[\"x\"]: x 位置

token[\"y\"]: y 位置

token[\"text\"]:要写入的文本

当 token[\"text\"] 不包含任何空格时,如何添加额外的空格。

此外,此问题仅在某些情况下发生。以下屏幕截图显示了如何使用单个空格成功查询。

Successful single spaced query

  • 我不认为 OCR 有问题。 Google Document AI json 响应非常准确。您可以在第一个屏幕截图中看到响应是单行距的。这个问题很不寻常,因为似乎没有任何理由为什么某些文本序列使用单个空格而其他文本序列需要双空格。上面的例子显示了句子“In the midst”如何在单词之间需要双空格,而最后一个链接显示了一个成功的单行距查询。你能解释一下“没有位置空格的纯文本”是什么意思吗?谢谢!

标签: reportlab


【解决方案1】:

对此不是 100% 确定,但我建议检查 Token.DetectedBreak 字段。 Type 有一个用于检测到中断类型的枚举,它有一个常规空间和宽空间的选项。检查检测到哪种类型的中断可能是值得的。

代码示例最近也进行了更新,展示了如何从 Document AI 输出中访问所有 OCR 数据。

https://cloud.google.com/document-ai/docs/handle-response#code_samples

【讨论】: