이 경우 단어 분할을 사용하고 싶습니다. 공백없이 영어 문장을 처리 할 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
를 사용할 수는 목록의 목록을 평평하게하는
놀랍습니다. 고마워요! 내가 찾던 것이 아주 훌륭하다. 나는 이것이 nltk corpora로 할 수 있다고 생각했지만, 나는 pyenzant로 일하게되어 기쁩니다! – Kookaburra
이 답변은 일종의 오래된 것으로 알고 있지만, 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 –