0

nltk 모듈을 사용하여 Python에서 단어를 분할하는 방법을 찾으려고합니다. 내가 가지고있는 원시 데이터가 토큰 화 된 단어의 목록 인 경우 내 목표에 도달하는 방법을 확신 할 수 없습니다.Python에서 nltk 모듈을 사용하여 단어 분할하기

['usingvariousmolecularbiology', 'techniques', 'toproduce', 'genotypes', 'following', 'standardoperatingprocedures', '.', 'Operateandmaintainautomatedequipment', '.', 'Updatesampletrackingsystemsandprocess', 'documentation', 'toallowaccurate', 'monitoring', 'andrapid', 'progression', 'ofcasework'] 

당신은 많은 단어가 붙어있다 참조 (즉, '에'와 'toproduce'하나 개의 문자열에 갇혀있다 '생산') 할 수있다. 이 PDF 파일에서 데이터를 근근이 살아남은 작품이며, 나는 붙어있는 단어를 분리하기 위해 파이썬에서 nltk 모듈을 사용하는 방법을 찾고 싶습니다. (즉, 'toproduce'를 'to'와 'produce'로 나눕니다. 'standardoperatingprocedures'를 'standard', 'operating', 'procedures'의 세 가지 단어로 나눕니다.

감사합니다.

답변

1

이 경우 단어 분할을 사용하고 싶습니다. 공백없이 영어 문장을 처리 할 NLTK의 단어 세분화 기능을 알지 못합니다. 대신 pyenchant을 사용할 수 있습니다. 나는 예제로써 만 다음 코드를 제공한다. (예제 목록에있는 문자열과 같이 비교적 짧은 문자열을 적당히 사용할 수는 있지만 긴 문자열이나 많은 문자열에 대해서는 비효율적입니다.) 수정이 필요하며 모든 세그먼트를 성공적으로 분할하지 못합니다 어떤 경우에도 문자열.

import enchant # pip install pyenchant 
eng_dict = enchant.Dict("en_US") 

def segment_str(chars, exclude=None): 
    """ 
    Segment a string of chars using the pyenchant vocabulary. 
    Keeps longest possible words that account for all characters, 
    and returns list of segmented words. 

    :param chars: (str) The character string to segment. 
    :param exclude: (set) A set of string to exclude from consideration. 
        (These have been found previously to lead to dead ends.) 
        If an excluded word occurs later in the string, this 
        function will fail. 
    """ 
    words = [] 

    if not chars.isalpha(): # don't check punctuation etc.; needs more work 
     return [chars] 

    if not exclude: 
     exclude = set() 

    working_chars = chars 
    while working_chars: 
     # iterate through segments of the chars starting with the longest segment possible 
     for i in range(len(working_chars), 1, -1): 
      segment = working_chars[:i] 
      if eng_dict.check(segment) and segment not in exclude: 
       words.append(segment) 
       working_chars = working_chars[i:] 
       break 
     else: # no matching segments were found 
      if words: 
       exclude.add(words[-1]) 
       return segment_str(chars, exclude=exclude) 
      # let the user know a word was missing from the dictionary, 
      # but keep the word 
      print('"{chars}" not in dictionary (so just keeping as one segment)!' 
        .format(chars=chars)) 
      return [chars] 
    # return a list of words based on the segmentation 
    return words 

당신이 볼 수 있듯이,이 방법 (아마도) 잘못 세그먼트 당신의 문자열의 하나

>>> from itertools import chain 
>>> list(chain.from_iterable(segment_str(chars) for chars in t)) 
"genotypes" not in dictionary (so just keeping as one segment)! 
['using', 'various', 'molecular', 'biology', 'techniques', 'to', 'produce', 'genotypes', 'following', 'standard', 'operating', 'procedures', '.', 'Operate', 'and', 'maintain', 'automated', 'equipment', '.', 'Updates', 'ample', 'tracking', 'systems', 'and', 'process', 'documentation', 'to', 'allow', 'accurate', 'monitoring', 'and', 'rapid', 'progression', 'of', 'casework'] 
:

>>> t = ['usingvariousmolecularbiology', 'techniques', 'toproduce', 'genotypes', 'following', 'standardoperatingprocedures', '.', 'Operateandmaintainautomatedequipment', '.', 'Updatesampletrackingsystemsandprocess', 'documentation', 'toallowaccurate', 'monitoring', 'andrapid', 'progression', 'ofcasework'] 
>>> [segment(chars) for chars in t] 
"genotypes" not in dictionary (so just keeping as one segment) 
[['using', 'various', 'molecular', 'biology'], ['techniques'], ['to', 'produce'], ['genotypes'], ['following'], ['standard', 'operating', 'procedures'], ['.'], ['Operate', 'and', 'maintain', 'automated', 'equipment'], ['.'], ['Updates', 'ample', 'tracking', 'systems', 'and', 'process'], ['documentation'], ['to', 'allow', 'accurate'], ['monitoring'], ['and', 'rapid'], ['progression'], ['of', 'casework']] 

그런 다음 chain를 사용할 수는 목록의 목록을 평평하게하는

+0

놀랍습니다. 고마워요! 내가 찾던 것이 아주 훌륭하다. 나는 이것이 nltk corpora로 할 수 있다고 생각했지만, 나는 pyenzant로 일하게되어 기쁩니다! – Kookaburra

+0

이 답변은 일종의 오래된 것으로 알고 있지만, set() 기본 매개 변수는 피곤할 것입니다. 시도하면 이상한 동작이 발생합니다. '[6] : segment_str ("tookapill ") Out [6] : [ 'to', 'okapi', 'll'] [7]에서 : segment_str ("tookapillinibiza ") "takeapillinibiza "는 사전에 없으므로 (하나의 세그먼트로 유지)! Out [7] : [ 'tookapillinibiza'] [8]에서 : segment_str ("tookapill") "tookapill"은 사전에 없으므로 (하나의 세그먼트로 유지)! Out [8] : [ 'tookapill'] ' 기본 없음에 추가하고 사용시 선택 함 : http://effbot.org/zone/default-values.htm –