python - 如何用连字符检查句子中的多个单词
问题描述
我有一个用连字符替换句子中的单个单词的功能,它工作正常我试图添加的是让用户输入由空格分隔的多个单词,并且该函数会审查它们。有没有办法做到这一点?我当前的代码附在下面。任何帮助表示赞赏。提前致谢。
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()
解决方案
您可以使用字符串替换:
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()
推荐阅读
- php - phpDocumentor 在我的代码中找不到 TODO 标记?
- parsing - Prolog 中的一元解析器(示例 DIMACS 文件)
- c++ - 不能使用字符串来命名我要创建的文件
- python - 如何在 URL 列表上抓取和执行 NLP
- azure - Azure 函数本地调试没有发生门户问题?
- c# - Xamarin.Forms VNDocumentCameraViewController Scanner如何在Android中实现类似
- c# - 使用 c# 客户端缺少授权标头
- javascript - 选择下拉项,触发点击事件,点击按钮并从网站提取输出
- docker - Docker 容器与私有网络/网站通信
- elasticsearch - ElasticSearch“无法镶嵌形状”索引有效地理形状时出错