찾다
백엔드 개발파이썬 튜토리얼Python을 사용하여 Word 문서에서 텍스트 및 이미지 추출

Word 문서에서 콘텐츠를 추출하면 데이터베이스에 콘텐츠 저장, 다른 프로그램으로 콘텐츠 가져오기, 인공 지능 교육 및 기타 문서 작성과 같은 다른 작업에 해당 콘텐츠를 사용할 수 있습니다. Python용 Spire.Doc을 사용하면 많은 복사 및 붙여넣기 또는 복잡한 코딩 없이 Word 문서에서 텍스트와 이미지를 쉽게 추출할 수 있습니다. 이 문서에서는 간단한 코드를 사용하여 Word 문서에서 텍스트와 이미지 콘텐츠를 추출하고 저장하는 방법을 설명합니다.

Python용 Spire.Doc 가져오기

이 도구를 사용하여 Word 문서를 편집하려면 먼저 해당 문서를 프로젝트로 가져와야 합니다. Python 공식 웹사이트 Spire.Doc에서 다운로드하거나 pip를 사용하여 직접 설치할 수 있습니다. 코드는 다음과 같습니다.

pip install Spire.Doc
pip install plum-dispatch==1.7.4
전체 화면 모드로 전환 전체 화면 모드 종료

Musterdokument

Python을 사용하여 Word 문서에서 텍스트 및 이미지 추출

Word 문서에서 텍스트를 추출하고 TXT 파일에 씁니다.

Python용

Spire.Doc의 Document.GetText() 메서드는 Word 문서의 모든 텍스트를 검색하여 문자열로 반환할 수 있습니다. 반환된 문자열을 저장을 위해 텍스트 파일에 쓸 수 있습니다. 단계는 다음과 같습니다.

  • 문서 개체를 생성합니다.
  • Word 문서를 로드하려면 Document.LoadFromFile() 메서드를 사용하세요.
  • Document.GetText() 메서드를 사용하여 문서에서 텍스트를 가져옵니다.
  • Den abgerufenen Text in eine Textdatei schreiben.

코드베슈필

파이썬

Copy
from turtle import st
from spire.doc import *
from spire.doc.common import *

def WriteAllText(fname:str,text:List[str]):
        fp = open(fname,"w")
        for s in text:
            fp.write(s)
        fp.close()

inputFile = "Beispiel.docx"
outputFile = "Extrahierter Text.txt"

#Document-Objekt erstellen  
document = Document()

#Word-Dokument laden
document.LoadFromFile(inputFile)

#Text aus Dokument abrufen
text = document.GetText()

#Text in Textdatei schreiben
WriteAllText(outputFile, text)
document.Close()
전체 화면 모드로 전환 전체 화면 모드 종료

추가 텍스트

Python을 사용하여 Word 문서에서 텍스트 및 이미지 추출

Word-Dokument extrahieren 및 speichern의 이미지

Das Extrahieren von Bildern ist etwas komplexer. den, ob dessen untergeordnete Objekte Bilder enthalten:

  • 문서 개체를 생성합니다.
  • Word 문서를 로드하려면 Document.LoadFromFile() 메서드를 사용하세요.
  • Eine Warteschlange für zusammengesetzte Objekte erstellen und die Dokumentenelemente hinzufügen.
  • Eine Liste zum Speichern der extrahierten Bilder erstellen.
  • Die Dokumentenelemente durchlaufen and die untergeordneten Objekte jedes Knotens durchlaufen, um zu prüfen, ob es sich um ein zusammengesetztes Objekt oder Bildobjekt handelt.
  • Prüfen, ob das untergeordnete Element ein Bildobjekt ist. Wenn ja, die Bilddaten extrahieren und zur Liste hinzufügen.
  • Prüfen, ob das untergeordnete Element ein zusammengesetztes Objekt ist. Wenn ja, zur Warteschlange hinzufügen und weiter prüfen.
  • Einen Ordner speichern의 이미지.

코드베슈필

파이썬

Copy
import queue
from spire.doc import * 
from spire.doc.common import *
import os

outputPath = "Bilder/"
inputFile = "Beispiel.docx"

if not os.path.exists(outputPath):
    os.makedirs(outputPath)

#Document-Objekt erstellen
document = Document()  

#Word-Dokument laden
document.LoadFromFile(inputFile)

#Warteschlange erstellen und Dokumentenelemente hinzufügen
nodes = queue.Queue()
nodes.put(document)

#Liste erstellen
images = []

#Dokumentenelemente durchlaufen
while nodes.qsize() > 0:
    node = nodes.get()
    for i in range(node.ChildObjects.Count):
        #Untergeordnetes Objekt des Dokumentenelements abrufen
        child = node.ChildObjects.get_Item(i)
        #Prüfen, ob es ein Bild ist
        if child.DocumentObjectType == DocumentObjectType.Picture:
            picture = child if isinstance(child, DocPicture) else None
            dataBytes = picture.ImageBytes
            #Zur Liste hinzufügen
            images.append(dataBytes)
        #Prüfen, ob es ein zusammengesetztes Objekt ist
        elif isinstance(child, ICompositeObject):
            #Zur Warteschlange hinzufügen
            nodes.put(child if isinstance(child, ICompositeObject) else None)

#Bilder speichern
for i, item in enumerate(images):
    fileName = "Bild-{}.png".format(i)
    with open(outputPath+fileName,'wb') as imageFile:
        imageFile.write(item)

document.Close()
전체 화면 모드로 전환 전체 화면 모드 종료

추가 이미지

Python을 사용하여 Word 문서에서 텍스트 및 이미지 추출

Der extrahierte Text wird mit angehängten Bewertungsinformationen gespeichert. Sie können die Bewertungsinformationen direkt am Anfang des Textes löschen.

Python용 Spire.Doc을 사용하여 Word 문서에서 텍스트와 이미지를 추출하는 방법을 소개합니다. Python용 Spire.Doc은 다른 많은 문서 작업을 지원합니다. 공식 웹사이트를 확인하거나 Spire.Doc 포럼에 가입하세요.

위 내용은 Python을 사용하여 Word 문서에서 텍스트 및 이미지 추출의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?May 03, 2025 am 12:11 AM

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.May 03, 2025 am 12:10 AM

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?May 03, 2025 am 12:06 AM

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?May 03, 2025 am 12:03 AM

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.May 03, 2025 am 12:01 AM

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

파이썬 목록을 어떻게 슬라이스합니까?파이썬 목록을 어떻게 슬라이스합니까?May 02, 2025 am 12:14 AM

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?May 02, 2025 am 12:09 AM

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?May 02, 2025 am 12:09 AM

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구