웹사이트 검색

Python에서 Whoosh 라이브러리를 사용하여 텍스트 검색 엔진 개발


Whoosh는 텍스트 색인을 생성한 다음 색인을 검색하기 위한 클래스와 함수로 구성된 Python 라이브러리입니다. 다양한 문서를 검토한 후 유사점을 찾거나 사전 정의된 몇 가지 조건을 기반으로 데이터를 가져와야 하는 애플리케이션을 구축한다고 가정해 보겠습니다. 또는 연구에서 프로젝트 제목이 언급된 횟수를 세고 싶다고 가정해 보겠습니다. 그러면 이 튜토리얼에서 우리가 만들고 있는 것이 도움이 될 것입니다.

시작하기

텍스트 검색 엔진을 구축하기 위해 whoosh 라이브러리를 사용하여 작업할 것입니다.

이 라이브러리는 Python과 함께 사전 패키지로 제공되지 않습니다. 따라서 pip 패키지 관리자를 사용하여 다운로드하고 설치하겠습니다.

whoosh 라이브러리를 설치하려면 아래 줄을 사용하십시오.

pip install whoosh

이제 아래 줄을 사용하여 스크립트로 가져올 수 있습니다.

from whoosh.fields import Schema, TEXT, ID
from whoosh import index

Python을 사용하여 텍스트 검색 엔진 구축

먼저, 필요할 때 색인화된 파일을 저장할 폴더를 정의하겠습니다.

import os.path
os.mkdir("dir")

다음으로 스키마를 정의해 보겠습니다. 스키마는 인덱스의 문서 필드를 지정합니다.

schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT(stored = True))
ind = index.create_in("dir", schema)
writer = ind.writer()
writer.add_document(title=u"doc", content=u"Py doc hello big world", path=u"/a") 
writer.commit()

이제 문서의 색인을 생성했으므로 검색합니다.

from whoosh.qparser import QueryParser
with ind.searcher() as searcher:
     query = QueryParser("content", ind.schema).parse("hello world")
     results = searcher.search(query, terms=True)
     for r in results:
         print (r, r.score)
         if results.has_matched_terms():
            print(results.matched_terms())

산출

다음과 같은 출력이 생성됩니다.

<Hit {'path': '/a', 'title': 'doc', 'content': 'Py doc hello big world'}> 
1.7906976744186047
{('content', b'hello'), ('content', b'world')}

예

전체 코드는 다음과 같습니다.

from whoosh.fields import Schema, TEXT, ID
from whoosh import index
import os.path
os.mkdir("dir")
schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT(stored = True))
ind = index.create_in("dir", schema)
writer = ind.writer()
writer.add_document(title=u"doc", content=u"Py doc hello big world", path=u"/a") 
writer.commit()

from whoosh.qparser import QueryParser
with ind.searcher() as searcher:
     query = QueryParser("content", ind.schema).parse("hello world")
     results = searcher.search(query, terms=True)
     for r in results:
         print (r, r.score)
         if results.has_matched_terms():
            print(results.matched_terms())

결론

이제 Python에서 텍스트 검색 엔진을 만드는 방법을 배웠습니다. 이를 사용하면 다양한 문서를 검색하여 몇 초 안에 유용한 콘텐츠를 추출할 수 있습니다. 또한 Python에서 Whoosh 라이브러리의 잠재력을 탐색했습니다.

관련기사: