Python 如何迭代文本并用字典值替换某些单词

Python 如何迭代文本并用字典值替换某些单词,python,dictionary,Python,Dictionary,我想创建一个搜索句子的东西,从中取出你想要的任何单词,并用替换词进行切换。这是我到目前为止得到的,但它只返回none而不是句子 def testing (): test_dic = {'dog' : 'Censored'} text = raw_input('Input your sentence here: ').lower() text = text.join(" ") for words in text: if words in test_

我想创建一个搜索句子的东西,从中取出你想要的任何单词,并用替换词进行切换。这是我到目前为止得到的,但它只返回none而不是句子

def testing ():
    test_dic = {'dog' : 'Censored'}
    text = raw_input('Input your sentence here: ').lower()
    text = text.join(" ")

    for words in text:
        if words in test_dic:
            for i, j in test_dic.iteritems():
                clean_text = text.replace(i, j)
            return clean_text

我是python新手,所以这可以解释我是否试图以错误的或非python的方式进行操作。有人能帮我吗?

您使用了
join
,您可能指的是
split
。在字典中还有一个无关的循环。下面的代码将遍历每个单词,并根据它是否作为键存在于字典中而保留或替换它

def testing ():
    test_dic = {'dog' : 'Censored'}
    text = raw_input('Input your sentence here: ').lower()
    text = text.split(" ")

    new_text = []
    for word in text:
        if word in test_dic:
            new_text.append(test_dic[word])
        else:
            new_text.append(word)
    return " ".join(new_text)

print testing()

下面是一种使用列表理解的方法:

def testing ():
   test_dic = {'dog' : 'Censored'}
   text = raw_input('Input your sentence here: ').lower()

   return ' '.join([test_dic.get(word, word) for word in text.split()])

请您提一下输入和输出示例。我想您想在第4行使用
split
而不是
join