2014-01-10 2 views
0

텍스트 파일에서 읽는 Python 프로그램을 작성하는 데 어려움을 겪고 있으며 나타나는 각 단어를 매핑하는 사전을 작성하고 있습니다. 파일에서 해당 단어 바로 뒤의 모든 단어 목록으로 이동하십시오. 단어 목록은 순서에 관계없이 중복 된 단어를 포함해야합니다.텍스트 파일을 읽고 각 단어를 매핑하는 사전을 작성하는 방법

예를 들어, "and" 키의 텍스트에 "and" 이후의 모든 단어를 나열하는 목록 ["then", "best", "after", ...]이있을 수 있습니다.

어떤 아이디어라도 도움이 될 것입니다.

+1

'defaultdict (list)'를 사용하면 파일을 읽고 각 행을 반복하는 방법을 알고 있다면 당신이 가고 싶은 곳으로 가야합니다. 더 구체적인 질문이 있으면 요청한 내용을 수정하십시오. – aelfric5578

+0

"붙어. 아무것도 없어"- 정말? 전혀? 어딘가에서 (파일을 파싱 할 수있는 코드 작성) 시작하면 질문이보다 구체화되고 구체화됩니다. – stewSquared

+0

내 코드가 도움이되는 것 같습니다. 고맙습니다. 나는 특별한 것은 없지만 당신의 질문을 업 그레 이드. 그러나 pythonista를 격려하는 것입니다! – eyquem

답변

0

사전이 필요하십니까?
텍스트가 길면 여러 항목에 대해 동일한 데이터를 여러 번 반복하는 데 많은 메모리가 필요합니다.
기능을 사용하는 경우 원하는 목록이 제공됩니다. 예 :

s = """In Newtonian physics, free fall is any motion 
of a body where its weight is the only force acting 
upon it. In the context of general relativity where 
gravitation is reduced to a space-time curvature, 
a body in free fall has no force acting on it and 
it moves along a geodesic. The present article 
concerns itself with free fall in the Newtonian domain.""" 

import re 

def say_me(word,li=re.split('\s+',s)): 
    for i,w in enumerate(li): 
     if w==word: 
      print '\n%s at index %d followed by\n%s' % (w,i,li[i+1:]) 

say_me('free') 

결과

free at index 3 followed by 
['fall', 'is', 'any', 'motion', 'of', 'a', 'body', 'where', 'its', 'weight', 'is', 'the', 'only', 'force', 'acting', 'upon', 'it.', 'In', 'the', 'context', 'of', 'general', 'relativity', 'where', 'gravitation', 'is', 'reduced', 'to', 'a', 'space-time', 'curvature,', 'a', 'body', 'in', 'free', 'fall', 'has', 'no', 'force', 'acting', 'on', 'it', 'and', 'it', 'moves', 'along', 'a', 'geodesic.', 'The', 'present', 'article', 'concerns', 'itself', 'with', 'free', 'fall', 'in', 'the', 'Newtonian', 'domain.'] 

free at index 38 followed by 
['fall', 'has', 'no', 'force', 'acting', 'on', 'it', 'and', 'it', 'moves', 'along', 'a', 'geodesic.', 'The', 'present', 'article', 'concerns', 'itself', 'with', 'free', 'fall', 'in', 'the', 'Newtonian', 'domain.'] 

free at index 58 followed by 
['fall', 'in', 'the', 'Newtonian', 'domain.'] 

assignement li=re.split('\s+',s) 인수로서 전달 된 객체에 re.split('\s+',s) 파라미터 li을 결합하는 방식이다.
이 바인딩은 한 번만 수행됩니다. 함수 정의를 해석기가 읽을 때 함수 개체를 만드는 순간입니다. 기본 인수로 정의 된 매개 변수입니다.

1

아이디어의 몇 :

  1. 당신의 출력을위한 collections.defaultdict을 설정합니다. 이것은 아직 존재하지 않는 키에 대한 기본값이있는 사전입니다 (이 경우 aelfric5578에서 제안하는대로 빈 list).
  2. 파일의 모든 단어 목록을 순서대로 작성하십시오.
  3. zip(lst, lst[1:])을 사용하여 연속적인 목록 요소 쌍을 만들 수 있습니다.
0

여기에 내가 할 것이었다

from collections import defaultdict 

# My example line : 
s = 'In the face of ambiguity refuse the temptation to guess' 

# Previous string is quite easy to tokenize but in real world, you'll have to : 
# Remove comma, dot, etc... 
# Probably encode to ascii (unidecode 3rd party module can be helpful) 
# You'll also probably want to normalize case 

lst = s.lower().split(' ') # naive tokenizer 

ddic = defaultdict(list) 

for word1, word2 in zip(lst, lst[1:]): 
    ddic[word1].append(word2) 

# ddic contains what you want (but is a defaultdict) 
# if you want to work with "classical" dictionnary, just cast it : 
# (Often it's not needed) 
dic = dict(ddic) 

미안 내가 해설자 아이디어를 훔치는 것 같다 경우, 그러나 이것은 내 프로젝트의 일부 (유사 문서 알고리즘을 미리 계산에 사용되는 거의 동일한 코드입니다)

관련 문제