首页 > 解决方案 > 如何用连字符检查句子中的多个单词

问题描述

我有一个用连字符替换句子中的单个单词的功能,它工作正常我试图添加的是让用户输入由空格分隔的多个单词,并且该函数会审查它们。有没有办法做到这一点?我当前的代码附在下面。任何帮助表示赞赏。提前致谢。

def replaceWords(text, word):
    word_list = text.split()
  
    result = ''
  
    hyphen = '-' * len(word)
  

    count = 0


    index = 0;
    for i in word_list:
  
        if i == word:
              
            
            word_list[index] = hyphen
        index += 1
  
    
    result =' '.join(word_list)
  
    return result

def main():
    sentence = input(str("enter a sentence: "))
    words = input(str("enter words to censor(separated by space): "))
    print(replaceWords(sentence, words))
  

if __name__== '__main__':
    main()

标签: python

解决方案


您可以使用字符串替换:

def replaceWords(text, words):
    censored_words = words.split()
    replace_character = "-"
    for censor in censored_words:
        text = text.replace(censor,replace_character*len(censor))
    
    return text

def main():
    sentence = input(str("enter a sentence: "))
    words = input(str("enter words to censor(separated by space): "))
    print(replaceWords(sentence, words))
  

if __name__== '__main__':
    main()

推荐阅读