2016-10-23 3 views
0

다음 문제가 있습니다. 이 코드는 해시 태그를 잡기에 완벽하지만 ... 두 번째 "while"에 차선이 완료된 것을 어떻게 넣을 수 있습니까?IndexError : 문자열 인덱스가 범위를 벗어났습니다. 한 번 더

나는이 차선을 넣을 경우

hash = '#hhhh #asdasd' 

코드 이뤄져 컴파일. 그 동안을 어떻게 바꿀 수 있습니까? 미리 감사드립니다. 예외 : 당신은 해시의 길이에 대한 확인이 없기 때문에 당신은 인덱스에 문제가

hash = '#hhhh #asdasd ' 
indexA = 0 
copy = '' 
indexB = indexA 

while indexA < len(hash): 
    indexB = indexA 
    copy = '' 

    if hash[indexA] == '#' and indexA + 1 < len(hash): 
     while hash[indexA + 1] not in {' ', '#'}: 
      indexA += 1 
      copy = hash[indexB:indexA + 1] 

     if len(copy) > 1: 
      print('newHashtag: ' + copy) 

     if hash[indexA + 1] == ' ': 
      indexA += 1 

    else: 
     indexA += 1 
+2

while indexA Li357

+1

이 코드는 제 Python 인터프리터에서 작동합니다. Btw,'hash'는 파이썬의 내장 함수입니다. 덮어 쓰는 것은 좋지 않습니다. – pivanchy

+0

당신이 무엇을하고 있는지 이해한다면 실제로 이것을 위해 정규 표현식을 사용해야합니다. 문자열이 항상 규칙적이면'split' 만 사용할 수도 있습니다. –

답변

1

: 여기

while hash[indexA + 1] not in {' ', '#'}: 
IndexError: string index out of range 

는 코드입니다. 이것은 작동합니다 : 당신이 문자열에 태그를 찾으려면

hash = '#hhhh #asdasd' 
indexA = 0 
copy = '' 
indexB = indexA 

while indexA < len(hash): 
    indexB = indexA 
    copy = '' 

    if hash[indexA] == '#' and indexA + 1 < len(hash): 
     while indexA + 1 < len(hash) and hash[indexA + 1] not in {' ', '#'}: 
      indexA += 1 
      copy = hash[indexB:indexA + 1] 

     if len(copy) > 1: 
      print('newHashtag: ' + copy) 

     if indexA + 1 < len(hash) and hash[indexA + 1] == ' ': 
      indexA += 1 

    else: 
     indexA += 1 
2

, 당신은 할 수있는 훨씬 쉽고 훨씬 파이썬 방법 사용 :

에 공백이없는 태그의 경우
some_string = "#tag1 #tag2 something else #tag3" 
tags = [tag.strip("#") for tag in some_string.split() if tag.startswith("#")] 

>>> print tags 
['tag1', 'tag2', 'tag3'] 

, 당신이 뭔가를 쓸 수 있습니다를 다음과 같이하십시오 :

some_string = "#tag1 #tag2 something else #tag3 #moretags#andmore" 
tags = [] 
for tag in some_string.split(): 
    if '#' in tag: 
     multi_tags = tag.split('#') 
     tags.extend([t for t in multi_tags if t]) 

>>> tags 
['tag1', 'tag2', 'tag3', 'moretags', 'andmore'] 
+0

OP 코드에 따르면 태그 사이에 공백이 없어 솔루션이 작동하지 않을 수 있습니다. – acw1668

+0

나는 너 같은 프로그래밍을 배우기를 원한다 –

+0

@Danicroquebelmar, 파이썬을 사용하여 수년간의 경험을 쌓은 후에 나처럼 프로그래밍 할 것이다.) 그러나 파이썬 기능을 사용하여 작업을 해결하려고 시도하지만 파이썬을 사용하여 기본 코드를 작성하지는 마십시오 :) – pivanchy

관련 문제