2011-10-06 4 views
2

안녕하세요 전 정규식을 다루지 않았으며 파이썬과 NLTK로 원시 텍스트를 사전 처리하려고합니다. 내가 사용하여 문서를 토큰 화하려고 할 때 :파이썬 정규 표현식 nltk 웹 사이트 추출

tokens = nltk.regexp_tokenize(corpus, sentence_re) 
sentence_re = r'''(?x) # set flag to allow verbose regexps 
    ([A-Z])(\.[A-Z])+\.? # abbreviations, e.g. U.S.A. 
| \w+(-\w+)*   # words with optional internal hyphens 
| \$?\d+(\.\d+)?%?  # currency and percentages, e.g. $12.40, 82% 
| \#?\w+|\@?\w+   # hashtags and @ signs 
| \.\.\.    # ellipsis 
| [][.,;"'?()-_`]  # these are separate tokens 
| ?:http://|www.)[^"\' ]+ # websites 
''' 

의 하나의 토큰으로 웹 사이트의 모든을 할 수 없습니다 :

print toks[:50] 
['on', '#Seamonkey', '(', 'SM', ')', '-', 'I', 'had', 'a', 'short', 'chirp', 'exchange', 'with', '@angie1234p', 'at', 'the', '18thDec', ';', 'btw', 'SM', 'is', 'faster', 'has', 'also', 'an', 'agile', '...', '1', '/', '2', "'", '...', 'user', 'community', '-', 'http', ':', '/', '/', 'bit', '.', 'ly', '/', 'XnF5', '+', 'ICR', 'http', ':', '/', '/'] 

이 어떤 도움이 크게 appreicated된다. 정말 고마워!

-Florie

이 토크 나이의 RegularExpressions에서
+2

자연어 구문 분석은 정규식 학습을 시작하기에 충분합니다. –

답변

3

는 토큰 당신이 같이 할 수있는 텍스트에서 추출하는 방법을 지정하는 데 사용됩니다. 나는 조금 사용하면 위의 많은 정규 표현식하는 혼동 해요,하지만 공백이 아닌 토큰 매우 간단한 토큰에 대해 다음과 같이 사용할 수 있습니다

>>> corpus.split() 
['this', 'is', 'a', 'sentence.', 'and', 'another', 'sentence.', 'my', 'homepage', 'is', 'http://test.com'] 
:

>>> corpus = "this is a sentence. and another sentence. my homepage is http://test.com" 
>>> nltk.regexp_tokenize(corpus, r"\S+") 
['this', 'is', 'a', 'sentence.', 'and', 'another', 'sentence.', 'my', 'homepage', 'is', 'http://test.com'] 

에 해당하는

또 다른 방법은 sent_tokenize NLTK 기능을 사용하여 수()와 nltk.word_tokenize() :

>>> sentences = nltk.sent_tokenize(corpus) 
>>> sentences 
['this is a sentence.', 'and another sentence.', 'my homepage is http://test.com'] 
>>> for sentence in sentences: 
    print nltk.word_tokenize(sentence) 
['this', 'is', 'a', 'sentence', '.'] 
['and', 'another', 'sentence', '.'] 
['my', 'homepage', 'is', 'http', ':', '//test.com'] 

텍스트 웹 사이트 - URL을이 migh 많이 포함 된 경우 비록 최선의 선택이 아닙니다. NLTK의 다른 토큰 화 프로그램에 대한 정보는 here입니다.

그냥 코퍼스에서 URL을 추출 할 경우이 같은 정규 표현식을 사용할 수 있습니다이 도움이

nltk.regexp_tokenize(corpus, r'(http://|https://|www.)[^"\' ]+') 

희망을. 이것이 여러분이 찾고자하는 답이 아니라면, 여러분이하고 싶은 것을 조금 더 정확하게 설명하고 토큰이 어떻게 보이길 원하는지 정확하게 설명해보십시오 (예를 들어 당신이 갖고 싶은 입출력 예). 그리고 우리가 도울 수 있습니다. 올바른 정규 표현식을 찾는다.