NLTK로 새 말뭉치 만들기
나는 종종 내 제목에 대한 답은 가서 문서를 읽는 것이라고 생각했지만 NLTK 책을 훑어 보았지만 답을 얻지 못했습니다. 저는 Python에 익숙하지 않습니다.
나는 많은 .txt
파일을 가지고 있고 NLTK가 말뭉치에 제공하는 말뭉치 기능을 사용할 수 있기를 원합니다 nltk_data
.
시도 PlaintextCorpusReader
했지만 더 이상 얻을 수 없습니다.
>>>import nltk
>>>from nltk.corpus import PlaintextCorpusReader
>>>corpus_root = './'
>>>newcorpus = PlaintextCorpusReader(corpus_root, '.*')
>>>newcorpus.words()
newcorpus
펑크를 사용 하여 문장을 어떻게 분할 합니까? punkt 함수를 사용해 보았지만 punkt 함수가 PlaintextCorpusReader
클래스를 읽을 수 없습니까?
분할 된 데이터를 텍스트 파일에 쓰는 방법에 대해서도 안내해 주시겠습니까?
PlaintextCorpusReader
적어도 입력 언어가 영어 인 경우 에는 이미 입력을 punkt tokenizer로 분할 한다고 생각합니다 .
def __init__(self, root, fileids,
word_tokenizer=WordPunctTokenizer(),
sent_tokenizer=nltk.data.LazyLoader(
'tokenizers/punkt/english.pickle'),
para_block_reader=read_blankline_block,
encoding='utf8'):
독자에게 단어와 문장 토크 나이저를 전달할 수 있지만 후자의 경우 기본값은 이미 nltk.data.LazyLoader('tokenizers/punkt/english.pickle')
.
단일 문자열의 경우 토크 나이 저는 다음과 같이 사용됩니다 ( 여기 에 설명되어 있음 , punkt 토크 나이저에 대한 섹션 5 참조).
>>> import nltk.data
>>> text = """
... Punkt knows that the periods in Mr. Smith and Johann S. Bach
... do not mark sentence boundaries. And sometimes sentences
... can start with non-capitalized words. i is a good variable
... name.
... """
>>> tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
>>> tokenizer.tokenize(text.strip())
몇 년 동안 작동 방식을 파악한 후 업데이트 된 튜토리얼은 다음과 같습니다.
텍스트 파일 디렉토리로 NLTK 코퍼스를 만드는 방법은 무엇입니까?
주요 아이디어는 nltk.corpus.reader 패키지를 사용하는 것입니다 . 영어로 된 텍스트 파일 디렉토리가있는 경우 PlaintextCorpusReader 를 사용하는 것이 가장 좋습니다 .
다음과 같은 디렉토리가있는 경우 :
newcorpus/
file1.txt
file2.txt
...
다음 코드 라인을 사용하면 코퍼스를 얻을 수 있습니다.
import os
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
corpusdir = 'newcorpus/' # Directory of corpus.
newcorpus = PlaintextCorpusReader(corpusdir, '.*')
참고 : (가)하는 PlaintextCorpusReader
기본값을 사용 nltk.tokenize.sent_tokenize()
하고 nltk.tokenize.word_tokenize()
영어 문장과 단어와 이러한 기능에 빌드하여 텍스트를하는 분할, 그것은 수도에 NOT 모든 언어에 대한 작업.
다음은 테스트 텍스트 파일 생성과 NLTK를 사용하여 말뭉치 생성 방법 및 다양한 수준에서 말뭉치에 액세스하는 방법을 포함한 전체 코드입니다.
import os
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
# Let's create a corpus with 2 texts in different textfile.
txt1 = """This is a foo bar sentence.\nAnd this is the first txtfile in the corpus."""
txt2 = """Are you a foo bar? Yes I am. Possibly, everyone is.\n"""
corpus = [txt1,txt2]
# Make new dir for the corpus.
corpusdir = 'newcorpus/'
if not os.path.isdir(corpusdir):
os.mkdir(corpusdir)
# Output the files into the directory.
filename = 0
for text in corpus:
filename+=1
with open(corpusdir+str(filename)+'.txt','w') as fout:
print>>fout, text
# Check that our corpus do exist and the files are correct.
assert os.path.isdir(corpusdir)
for infile, text in zip(sorted(os.listdir(corpusdir)),corpus):
assert open(corpusdir+infile,'r').read().strip() == text.strip()
# Create a new corpus by specifying the parameters
# (1) directory of the new corpus
# (2) the fileids of the corpus
# NOTE: in this case the fileids are simply the filenames.
newcorpus = PlaintextCorpusReader('newcorpus/', '.*')
# Access each file in the corpus.
for infile in sorted(newcorpus.fileids()):
print infile # The fileids of each file.
with newcorpus.open(infile) as fin: # Opens the file.
print fin.read().strip() # Prints the content of the file
print
# Access the plaintext; outputs pure string/basestring.
print newcorpus.raw().strip()
print
# Access paragraphs in the corpus. (list of list of list of strings)
# NOTE: NLTK automatically calls nltk.tokenize.sent_tokenize and
# nltk.tokenize.word_tokenize.
#
# Each element in the outermost list is a paragraph, and
# Each paragraph contains sentence(s), and
# Each sentence contains token(s)
print newcorpus.paras()
print
# To access pargraphs of a specific fileid.
print newcorpus.paras(newcorpus.fileids()[0])
# Access sentences in the corpus. (list of list of strings)
# NOTE: That the texts are flattened into sentences that contains tokens.
print newcorpus.sents()
print
# To access sentences of a specific fileid.
print newcorpus.sents(newcorpus.fileids()[0])
# Access just tokens/words in the corpus. (list of strings)
print newcorpus.words()
# To access tokens of a specific fileid.
print newcorpus.words(newcorpus.fileids()[0])
마지막으로, 텍스트 디렉토리를 읽고 다른 언어로 NLTK 코퍼스를 생성하려면 먼저 문자열 /베이스 스트링 입력을 받아 이러한 출력을 생성 하는 파이썬 호출 가능 단어 토큰 화 및 문장 토큰 화 모듈이 있는지 확인해야합니다 .
>>> from nltk.tokenize import sent_tokenize, word_tokenize
>>> txt1 = """This is a foo bar sentence.\nAnd this is the first txtfile in the corpus."""
>>> sent_tokenize(txt1)
['This is a foo bar sentence.', 'And this is the first txtfile in the corpus.']
>>> word_tokenize(sent_tokenize(txt1)[0])
['This', 'is', 'a', 'foo', 'bar', 'sentence', '.']
>>> import nltk
>>> from nltk.corpus import PlaintextCorpusReader
>>> corpus_root = './'
>>> newcorpus = PlaintextCorpusReader(corpus_root, '.*')
"""
if the ./ dir contains the file my_corpus.txt, then you
can view say all the words it by doing this
"""
>>> newcorpus.words('my_corpus.txt')
참고 URL : https://stackoverflow.com/questions/4951751/creating-a-new-corpus-with-nltk
'your programing' 카테고리의 다른 글
여러 활동에서 Android 애플리케이션을 어떻게 테스트합니까? (0) | 2020.10.10 |
---|---|
로그인에서 요청한 데이터베이스 "테스트"를 열 수 없습니다. (0) | 2020.10.10 |
SQL Server에서 RegEx 사용 (0) | 2020.10.10 |
flexbox 열 자식의 높이 100 % (0) | 2020.10.10 |
개발 환경 설정을 자동화하는 방법은 무엇입니까? (0) | 2020.10.10 |