2014-04-12 4 views
-1

Problem statement : text와 word 문자열을 입력으로 사용하는 censor라는 함수를 작성하십시오. 그것은이 훨씬 더 복잡보다PYTHON IndexError : 문자열 인덱스가 범위를 벗어났습니다.

def censor(text, word): 
    i = 0 
    j = 0 
    ans = "" 

    while i<len(text): 
     while text[j] == word[j]: 
      j = j + 1 
     if text[j+1] == " " or j+1 == len(text): 
      while i<j: 
       ans += "*" 
       i = i + 1 
      ans += " " 
      i = i + 1 
     else: 
      while text[j] != " ": 
       j = j + 1 
      while i<=j: 
       ans += text[i] 
       i = i + 1 

     i = i + 1 
     j = j + 1 

    return ans 

print censor("how are you? you are not fine.","you") 

그러나 나는 다음과 같은 오류가 발생하고,

Traceback (most recent call last): 
    File "python", line 27, in <module> 
    File "python", line 7, in censor 
IndexError: string index out of range 
+0

내가 코드 카데미에 문제를했던뿐만 아니라 : 귀하의 경우 , 당신은 단어의 길이의 사용과 텍스트의 단어를 일치하도록해야한다. 이것은 실제로 복잡하지 않아도됩니다. –

답변

1

, 당신은 별표

여기

내 코드가 대체 선택한 단어로 텍스트를 반환해야합니다 그럴 필요가있다. 당신은이 작업을 수행 할 수 있습니다

def censor(text, censored_word): 
    repl = '*'*len(censored_word) 
    return ' '.join([repl if word == censored_word else word for word in text.split()]) 

은 여러 가지고 싶다면 : 당신이 검열 할 단어 youth 검열 할 수 있지만 you을 원하는가하지 않으려면

def censor(text, censored_word): 
    return text.replace(censored_word, '*'*len(censored_word)) 

>>> censor('How are you? Are you okay?', 'you') 
'How are ***? Are *** okay?' 

, 여기 방법 검열 단어 :

def censor(text, censored_words): 
    return ' '.join(['*'*len(word) if word in censored_words else word for word in text.split()]) 

인덱스 오류 처리, 그것은 밖으로 인쇄 인덱스 및 그림 오 종종 도움이된다 왜 인덱스가 필요한 범위 내에 있지 않은지

+0

또한이 방법은 검열 될 단어가 부분적으로 문자열로 나타날 때이를 대체합니다. '검열 관 ("젊음", "너") == "*** th". 이것이 일어나지 않을 경우 텍스트를 개별 단어로 분리 한 다음 입력과 동일한 모든 단어를 대체하는 것이 더 나은 방법입니다. – l4mpi

+0

@ l4mpi 그 해결책을 추가 할 것입니다. –

0

문자열을 바꾸려면 파이썬에서 string replace을 사용하는 것이 좋습니다.

def censor(text, word): 
    i = 0 
    j = 0 
    ans = "" 
    wl=len(word) 

    while i<(len(text)): 
     if word==text[i:i+wl]: 
      ans=ans+'*'*wl 
      i=i+wl 
     else: 
      ans=ans+text[i] 
      i = i + 1 

    return ans 

print censor("how are you? you are not fine.","you") 
+0

왜 그렇게 복잡합니까? 모든 것은 하나의 짧고 단순한 라인에서 할 수 있습니다 ... –

관련 문제