Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建定义以替换Python中句子中的单词_Python_Python 3.x - Fatal编程技术网

创建定义以替换Python中句子中的单词

创建定义以替换Python中句子中的单词,python,python-3.x,Python,Python 3.x,我知道如何在不使用replace函数的情况下替换普通for循环中的单个字母,但我不知道如何在具有3个参数的定义上进行替换。每例 def substitute(sentence, target, replacement) 基本上,它将像替换(“海滩很美”,“海滩”,“天空”)并返回天空很美。如何在不使用替换或查找功能的情况下执行此操作? 谢谢 我想这就是你要找的 def replace_word(sentence, target, replacement): newSentence =

我知道如何在不使用replace函数的情况下替换普通for循环中的单个字母,但我不知道如何在具有3个参数的定义上进行替换。每例

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
    将单词与空格连接起来

你试着解决这个问题了吗?我试着在句子中为target做些什么,然后如果target在句子中,那么target=替换并返回单词,但它不起作用anything@Jonathan您应该提供您尝试的示例代码,因此,我们可以帮助您解决您的代码或算法可能存在的任何问题。我在那里编辑了@ILIMT这里有一些缩进问题@Jonathant当OP需要没有替换函数的解决方案时,他会使用替换函数。他说他知道如何使用for循环替换,但他不知道如何创建替换函数。他从未说过他不想使用替换函数“在不使用替换或查找函数的情况下,如何做到这一点?”OP的问题是:“在不使用替换或查找函数的情况下,如何做到这一点?”哦,srry没有读到,但是您的输出不会在每个单词后添加空格,请更正它。
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'