檢測兩個 Word 檔案之間的差異是開發人員在處理合約、報告或法律文件時的常見需求。 Aspose.BarCode Cloud SDK for Python 提供了強大的函式庫,可與 Aspose.Words Cloud SDK for Python 結合,以程式方式比較 Word 文件中的文字。 在本指南中,您將設定環境、將文件上傳至 Aspose Cloud 儲存、配置比較選項、執行比較,並取得帶有追蹤變更的結果文件。您還將看到如何使用 cURL 直接呼叫 REST 以取得相同結果。

環境準備 - 前置條件與設定

在開始之前,請確保您具備以下條件:

  • 在本機安裝 Python 3.8 或更新版本。
  • 擁有一個 Aspose Cloud 帳戶,具備 client_idclient_secret(可在 Aspose Cloud 儀表板中取得)。
  • 取得 Aspose Cloud 儲存空間的存取權限,以便處理暫存檔案。

使用 pip 安裝 BarCode SDK:

pip install aspose-barcode-cloud

您還需要 Aspose.Words Cloud SDK for Python,它負責處理 Word 特定的操作:

pip install asposewordscloud

將您的憑證設定為環境變數,或在程式碼中替換佔位符:

import os
client_id = os.getenv("ASPOSE_CLIENT_ID")
client_secret = os.getenv("ASPOSE_CLIENT_SECRET")

SDK 將使用這些值對 Aspose Cloud 服務進行驗證。環境準備就緒後,我們即可繼續實作。

在 Python 中比較 Word 文件的文字:逐步說明

第一步:載入來源文件

首先,配置您的 Aspose Cloud 憑證,以便 SDK 能夠進行身份驗證,並且您可以在 Python 中比較 Word 文檔中的文字。

from asposewordscloud import WordsApi, Configuration

config = Configuration(client_id=client_id, client_secret=client_secret)
words_api = WordsApi(config)

步驟 2:上傳來源和目標文件

上傳您想要比較的兩個 DOCX 檔案。輔助函式抽象了上傳過程。

def upload(local_file, remote_name):
    with open(local_file, "rb") as f:
        words_api.upload_file(request={"path": f"TempCompare/{remote_name}", "file": f})

upload("doc1.docx", "doc1.docx")
upload("doc2.docx", "doc2.docx")

步驟 3:設定比較選項

接下來,設定 CompareOptions 以定義 SDK 在 Python 中比較 Word 文件文字的方式,例如忽略大小寫或註解。

from asposewordscloud.models import CompareOptions

compare_opts = CompareOptions(
    author="PythonComparer",
    compare_options="IgnoreCase,IgnoreComments,IgnoreFormatting",
    file_path="TempCompare/doc2.docx",
    revision_author="PythonComparer",
    revision_date_time="2023-01-01T00:00:00Z"
)

步驟 4:執行文件比較

現在呼叫 compare_document 方法,以實際比較 Python 中 Word 文件的文字,並產生修訂追蹤的結果。

compare_result = words_api.compare_document(
    request={
        "name": "doc1.docx",
        "compare_data": compare_opts,
        "folder": "TempCompare"
    }
)

第5步:檢索並保存結果

最後,將生成的文件寫入磁碟並清理臨時檔案。

with open("compare_result.docx", "wb") as out_file:
    out_file.write(compare_result.document)

words_api.delete_file(request={"path": "TempCompare/doc1.docx"})
words_api.delete_file(request={"path": "TempCompare/doc2.docx"})

在 Python 中比較 Word 文件的文字 - 完整實作與完整程式碼範例

以下程式碼示範了在 Python 中使用 Aspose APIs 比較 Word 文件中文本的完整工作流程。

import os
from asposewordscloud import WordsApi, Configuration
from asposewordscloud.models import CompareOptions

# ----------------------------------------------------------------------
# Configuration – set your Aspose Cloud credentials in environment variables
# ----------------------------------------------------------------------
client_id = os.getenv("ASPOSE_CLIENT_ID")
client_secret = os.getenv("ASPOSE_CLIENT_SECRET")
config = Configuration(client_id=client_id, client_secret=client_secret)

# ----------------------------------------------------------------------
# Initialize the Words API client
# ----------------------------------------------------------------------
words_api = WordsApi(config)

# ----------------------------------------------------------------------
# Local file paths (replace with your actual files)
# ----------------------------------------------------------------------
source_path = "doc1.docx"
target_path = "doc2.docx"
result_path = "compare_result.docx"

# ----------------------------------------------------------------------
# Remote folder in Aspose Cloud storage where temporary files are kept
# ----------------------------------------------------------------------
remote_folder = "TempCompare"

# ----------------------------------------------------------------------
# Helper to upload a local file to Aspose Cloud storage
# ----------------------------------------------------------------------
def upload(local_file, remote_name):
    with open(local_file, "rb") as f:
        words_api.upload_file(request={"path": f"{remote_folder}/{remote_name}", "file": f})

# ----------------------------------------------------------------------
# Upload source and target documents
# ----------------------------------------------------------------------
upload(source_path, source_path)
upload(target_path, target_path)

# ----------------------------------------------------------------------
# Set up comparison options
# ----------------------------------------------------------------------
compare_opts = CompareOptions(
    author="PythonComparer",
    compare_options="IgnoreCase,IgnoreComments,IgnoreFormatting",
    file_path=f"{remote_folder}/{target_path}",
    revision_author="PythonComparer",
    revision_date_time="2023-01-01T00:00:00Z"
)

# ----------------------------------------------------------------------
# Perform the comparison
# ----------------------------------------------------------------------
try:
    compare_result = words_api.compare_document(
        request={
            "name": source_path,
            "compare_data": compare_opts,
            "folder": remote_folder
        }
    )
    # The API returns the resulting document as a byte array
    with open(result_path, "wb") as out_file:
        out_file.write(compare_result.document)
finally:
    # ------------------------------------------------------------------
    # Clean up remote temporary files
    # ------------------------------------------------------------------
    words_api.delete_file(request={"path": f"{remote_folder}/{source_path}"})
    words_api.delete_file(request={"path": f"{remote_folder}/{target_path}"})

注意: 此程式碼範例示範了核心功能。在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。如果遇到任何問題,請參閱官方文件或聯繫支援團隊尋求協助。

使用 cURL 透過 REST API 執行文件比較

以下是使用 REST API 在 Python 操作中執行相同的 Word 文件文字比較的 cURL 命令。

  1. 驗證並取得存取權杖
curl -X POST "https://api.aspose.cloud/connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
  1. 上傳來源檔案
curl -X PUT "https://api.aspose.cloud/v4.0/words/TempCompare/doc1.docx" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/octet-stream" \
  --data-binary "@doc1.docx"
  1. 上傳目標檔案
curl -X PUT "https://api.aspose.cloud/v4.0/words/TempCompare/doc2.docx" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/octet-stream" \
  --data-binary "@doc2.docx"
  1. 執行比較
curl -X POST "https://api.aspose.cloud/v4.0/words/doc1.docx/compare" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
        "compareOptions": {
            "author": "PythonComparer",
            "compareOptions": "IgnoreCase,IgnoreComments,IgnoreFormatting",
            "filePath": "TempCompare/doc2.docx",
            "revisionAuthor": "PythonComparer",
            "revisionDateTime": "2023-01-01T00:00:00Z"
        }
      }' -o compare_result.docx
  1. 下載輸出檔案
curl -X GET "https://api.aspose.cloud/v4.0/words/TempCompare/compare_result.docx" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -o compare_result.docx

如需了解請求正文和其他參數的詳細資訊,請參閱官方 API 文件

結論

本文示範了如何在 Python 中使用 Aspose.BarCode Cloud SDK for Python 比較 Word 文件中的文字。透過設定憑證、上傳檔案、配置比較選項以及呼叫 compare API 等步驟,您可以在應用程式中自動化文件差異工作流程。請記得取得適用於正式環境的授權;臨時授權可在 臨時授權頁面 取得,完整授權資訊則列於產品頁面。使用這些工具,將文件比較整合到您的 Python 專案中變得簡單且可靠。

常見問題

  • Aspose.BarCode Cloud SDK for Python 如何協助我在 Python 中比較 Word 文件的文字? 該 SDK 與 Aspose.Words Cloud SDK for Python 共同運作,可上傳 DOCX 檔案、設定比較選項,並產生帶有修訂追蹤的結果,以突顯差異。請參閱 Aspose.BarCode Cloud SDK for Python 產品頁面了解詳細資訊。

  • 我可以有效地比較大型 Word 檔案嗎?
    是的。透過使用 compare_document API,您可以從 Aspose Cloud 儲存體串流大型 DOCX 檔案,服務在伺服器端處理,從而減少您機器的記憶體使用。請參閱官方文件以獲得效能提示。

  • 什麼檔案格式支援比較?
    API 主要支援 DOCX 檔案,但您也可以在將 DOC 檔案轉換為 DOCX 後,使用 Aspose.Words 進行比較。所有格式名稱均為大寫,例如 DOCX、PDF。

  • 我需要許可證才能在生產環境中運行嗎?
    臨時許可證可在臨時許可證頁面取得。對於生產環境的使用,您應該購買完整許可證,具體說明請參閱產品頁面。

Read More