2017-03-25 1 views
0

내 의견은 코드 아래에 있습니다. 내 프로그램이 단어를 검열합니다. 그것은 하나의 단어와 많은 단어 모두를 위해 작동합니다. 많은 단어에 대해 프로그램을 작동시키는 데 어려움을 겪고있었습니다. 그것은 또한 검열 된 공간을 가진 문장을 인쇄 할 것입니다. 그래도 작동하도록 코드를 찾았지만 이해하지 못합니다.코드를 다시 작성하는 방법

sentence = input("Enter a sentence:") 
word = input("Enter a word to replace:") 
words = word 
def censorWord(sentence,word): 
    # I would like to rewrite this code in a way I can understand and read clearer. 
    return " ".join(["-"*len(item) if item in word else item for item in sentence.split()]) 

def censorWords(sentence,words): 
    words1 = words.split() 
    for w in words1: 
    if w in sentence: 
     return replaceWord(sentence,word) 

print(censorWords(sentence,words)) 

답변

0

데프 censorWord (문장, 단어) :

result = [] #list to store the new sentence words 
eachword = sentence.split() #splits each word in the sentence and store in a seperate array element 
for item in eachword: #iterates the list until last word 
    if item == word: #if current list item matches the given word then insert - for length of the word 
     item = "-"*len(word) 
    result.append(item) #add the word to the list 
return " ".join(result) #join all the words in the list with space in between 
+0

이제 알겠습니다! 이것은 효과가 있었지만 len()에서 'item'으로 '=='를 'in'으로, 'word'를 'item'으로 변경했습니다. –

+0

'item'과 'word'는 같은 값을 가지므로 동일합니다. == 값은 두 값이 같은지 비교하는 반면 keyword는 word2가 word2에 있는지 여부를 확인합니다. 예 : '노란색'으로 '소리 지르다' –

0

당신은 다시 작성할 수 있습니다 :

s = " ".join(["-" * len(item) if item in word else item for item in sentence.split()]) 

속으로 :

arr = [] 
for item in sentence.split(): 
    if item in word: 
     arr.append("-" * len(item)) 
    else: 
     arr.append(item) 

s = " ".join(arr) 

그것은 기본적으로 분할 sentence 간격으로. 그런 다음 현재 itemword에 있으면 하이픈으로 자체 길이로 바뀝니다.

0

당신은 조금 censorWord() 문장의 모든 단어를 검열하고 그 처리의 중간에 같은 일을하지만 return의 일을하려고처럼 censorWords() 보이는 혼동이 될 것으로 보인다. 예를 들어,

자세한 설명 변수 이름을 아마 그것을 명확하게 것 하나 라이너 다운을 깨는 : : 그냥 censorWord()보고 당신은 항상 for 루프에이 바꿀 수 있지만, 지능형리스트가 공통 부분

def redact(word): 
    return '-'*len(word) 

def censorWord(sentence, censored_words): 
    words = sentence.split() 
    return " ".join([redact(word) if word in censored_words else word for word in words]) 

그리고 파이썬의 당신은 그들과 함께 편안하게해야합니다

def censorWord(sentence, censored_words): 
    words = sentence.split() 
    clean_sentence = [] 
    for word in words: 
     if word in censored_words: 
      clean_sentence.append(redact(word)) 
     else: 
      clean_sentence.append(word) 

    return " ".join(clean_sentence) 
관련 문제