2014-07-01 3 views
0

무한 루프가 있다고 생각합니까? 검색 용어가 키가되는 사전과 my_string에서 해당 키가있는 인덱스를 만들었습니다. 나는 각 검색어에 대한 색인으로 나열된 my_string에있는 모든 일치 목록을 가진 search_dict를 만들고 싶습니다.문자열에있는 모든 일치 항목의 색인을 찾아 사전에 검색어와 색인을 추가합니다.

수백만 개의 항목이있는 항목을 제외하고 내 search_dict는 채워지지 않습니다.

my_string='Shall I compare thee to a summer\'s day?' 
#string_dict has only a single index as a value where its key was found in my_string 
string_dict={'a': 36, ' ': 34, 'e': 30, '': 39, 'h': 17, 'm': 29, 'l': 4, 'o': 22, 'e ': 19, 's': 33, 'r': 31, 't': 21, ' t': 20, 'e t': 19} 

#I'd like search_dict to have all indices for key matches in my_string 
search_dict=dict() 
for key in string_dict: 
    search_dict[key]=list() 
for item in search_dict: 
    start=0 
    end=len(my_string) 
    found=my_string.find(item,start,end) 
    while start<end: 
     if found>=0: 
      search_dict[key].append(found) 
      start=found+len(item) 
      found=my_string.find(item,start,end) 
     else: 
      break 
print search_dict 

나는 또한 아래 변경을 시도했다. 아직도 my_string.find가 -1 (발견되지 않음)이되면 루프가 다음 검색 키 반복을 위반하지 않는 이유는 확실하지 않습니다.

 else: 
      break 
#with 
     if found<0: 
      break 
+0

코드 검토를 찾고 있습니까? –

+0

나는 이렇게함으로써 리뷰를하는 것이 도움이 될 것입니다. 나는 왜 그것이 영원히 반복하는지 이해하지 못한다. – 12345678910111213

+0

네, 무한 루프가 있습니다. 두 번째 while 문에서 조건을 확인하십시오. – senderle

답변

1

하위 문자열을 찾고 문자가 아닌 경우 정규식이 가장 잘 작동한다고 생각합니다.

>>> import re 
>>> my_string='Shall I compare thee to a summer\'s day?' 
>>> search_items = ['a', ' ', 'e', 'h', 'm', 'l', 'o', 'e ', 's', 'r', 't', ' t', 'e t'] 
>>> results_dict = {} 
>>> for search_item in search_items: 
...  results_dict[search_item] = [m.start() for m in re.finditer(search_item, my_string)] 
... 
>>> for elem in results_dict: 
...  print("%s: %s" % (elem, results_dict[elem])) 
... 
a: [2, 12, 24, 36] 
: [5, 7, 15, 20, 23, 25, 34] 
e: [14, 18, 19, 30] 
h: [1, 17] 
m: [10, 28, 29] 
l: [3, 4] 
o: [9, 22] 
e : [14, 19] 
s: [26, 33] 
r: [13, 31] 
t: [16, 21] 
t: [15, 20] 
e t: [14, 19] 

질문에 명시되지 않은 내용이지만 결과의 값은 부분 문자열의 시작 위치입니다.

+0

사전의 키나 목록의 항목을 검색하는 데 사용할 수 있습니다. 목록을 만드는 것을 피하는 것이 목표였습니다. 이것은 내 문제를 해결합니다. – 12345678910111213

0

원래 문제는 @senderle에서 발견되었습니다. len = 0 인 사전에서 항목이 무한 루프가 발생했습니다. 이 문제를 해결하기위한 조건을 삽입했습니다. @ 슬릭이 문제에 대한 최선의 해결책을 제시했습니다.

my_string='Shall I compare thee to a summer\'s day?' 
string_dict={'a': 36, ' ': 34, 'e': 30, '': 39, 'h': 17, 'm': 29, 'l': 4, 'o': 22, 'e ': 19, 's': 33, 'r': 31, 't': 21, ' t': 20, 'e t': 19} 

search_dict=dict() 
for key in string_dict: 
    search_dict[key]=list() 
for item in search_dict: 
    start=0 
    end=len(my_string) 
    found=my_string.find(item,start,end) 
    while start<end: 
     if found>=0: 
      search_dict[item].append(found) 
      start=found+len(item) 
      if len(item)==0: #Fixed! 
       break 
      found=my_string.find(item,start,end) 
     else: 
      break 
print search_dict 
관련 문제