创建定义以替换Python中句子中的单词
我知道如何在不使用replace函数的情况下替换普通for循环中的单个字母,但我不知道如何在具有3个参数的定义上进行替换。每例创建定义以替换Python中句子中的单词,python,python-3.x,Python,Python 3.x,我知道如何在不使用replace函数的情况下替换普通for循环中的单个字母,但我不知道如何在具有3个参数的定义上进行替换。每例 def substitute(sentence, target, replacement) 基本上,它将像替换(“海滩很美”,“海滩”,“天空”)并返回天空很美。如何在不使用替换或查找功能的情况下执行此操作? 谢谢 我想这就是你要找的 def replace_word(sentence, target, replacement): newSentence =
def substitute(sentence, target, replacement)
基本上,它将像
替换(“海滩很美”,“海滩”,“天空”)
并返回天空很美。如何在不使用替换或查找功能的情况下执行此操作?
谢谢
我想这就是你要找的
def replace_word(sentence, target, replacement):
newSentence = ""
for word in sentence.split(" "):
if word == target:
newSentence += replacement
else:
newSentence += word
newSentence += " "
return newSentence.rstrip(" ")
试试这个这是一种方法
def replace_word(sentence, target, replacement):
newSentenceLst = []
for word in sentence.split():
if word == target:
newSentenceLst.append(replacement)
else:
newSentenceLst.append(word)
return ' '.join(newSentenceLst)
res = replace_word("The beach is beautiful", "beach", "sky")
# 'The sky is beautiful'
解释
- 缩进在Python中至关重要。学习如何正确使用它
- 使用
将句子拆分为单词str.split
- 初始化列表并通过
向列表中添加单词list.append
- 如果单词等于您的目标,则通过
/If
使用替换else
- 最后使用
将单词与空格连接起来str.join
import re
def substitue(sentence,target,replacement):
x=re.sub("[^\w]", " ", sentence).split()
x = [word.replace(target,replacement) for word in x]
sent=" ".join(x)
return sent
def replace_word(sentence, target, replacement):
newSentenceLst = []
for word in sentence.split():
if word == target:
newSentenceLst.append(replacement)
else:
newSentenceLst.append(word)
return ' '.join(newSentenceLst)
res = replace_word("The beach is beautiful", "beach", "sky")
# 'The sky is beautiful'