, 파일이 'UTF8'에 당신이 Python2를 사용하는 경우 io.open()
에 encoding='utf8'
매개 변수를 사용하는 경우, 그것은 더 나은 수 있습니다 :
import io
from nltk import word_tokenize, sent_tokenize
with io.open('file.txt', 'r', encoding='utf8') as fin:
document = []
for line in fin:
tokens += [word_tokenize(sent) for sent in sent_tokenize(line)]
Python3이라면 다음과 같이하면됩니다 :
from nltk import word_tokenize
with open('file.txt', 'r') as fin:
document = []
for line in fin:
tokens += [word_tokenize(sent) for sent in sent_tokenize(line)]
Do tak http://nedbatchelder.com/text/unipain.html 토큰 화에 관해서는
에서 EA의 모습, 우리가 가정하면 각 라인은 하나 이상의 문장으로 구성 될 수 단락의 일종을 포함, 우리는 먼저 전체를 저장하는 목록을 초기 싶습니다 문서 :
for line in fin:
sentences = sent_tokenize(line)
그런 다음 우리는 t들로 문장을 분할 :
document = []
그런 다음 우리는 라인을 통해 반복하고 문장들로 라인을 분할 okens : 우리가 토큰 화 된 문장을 저장하기 위해 문서 목록을 업데이트 할 때문에
token = [word_tokenize(sent) for sent in sent_tokenize(line)]
, 우리는 사용
document = []
for line in fin:
tokens += [word_tokenize(sent) for sent in sent_tokenize(line)]
은 권장하지 않음! (한 줄에서 계속 가능) :
[email protected]:~$ cat file.txt
this is a paragph. with many sentences.
yes, hahaah.. wahahha...
[email protected]:~$ python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import io
>>> from itertools import chain
>>> from nltk import sent_tokenize, word_tokenize
>>> list(chain(*[[word_tokenize(sent) for sent in sent_tokenize(line)] for line in io.open('file.txt', 'r', encoding='utf8')]))
[[u'this', u'is', u'a', u'paragph', u'.'], [u'with', u'many', u'sentences', u'.'], [u'yes', u',', u'hahaah..', u'wahahha', u'...']]
첫 번째 디코딩 후 소문자. 그렇지 않으면 비 ASCII 문자로 잘못된 동작이 발생합니다. – alexis