python - 一个基本的 python 函数,用于检查替换句子中的单词

标签 python

我正在尝试构建一个简单的函数来审查句子中的特定单词。例如 "hello hello hi""***** ***** hi" 如果我输入 censor("hello hello hi", "你好”)。假设我不会收到带有大写字母或空字符串的标点符号和句子。

在网上研究后,我了解到有更简单的解决方案,例如:

def censor(text, word):
    return text.replace(word, "*" * len(word)) 

我还是想从学习的角度来理解,我在下面更复杂的代码中做错了什么。

def censor(text,word):
    split_text = text.split()
    length = len(word)
    for item in split_text:
        if item == word:
            item = ("*" * length)
        else:
            item = item
    return " ".join(split_text)

最佳答案

我想出的解决方案稍微简单一些,可以完成工作。

1.我确保两个参数都是一个字符串,然后检查该词是否在文本字符串中。 2.然后如果这个词在文本字符串中,我得到这个词的长度。 3.然后我用 * 替换字符串中的单词,但是很多时候这个单词很长。

def censor(text,word):
t=str(text)
w=str(word)
if w in t:
    l=len(w)
    item = ("*" * l)
    return t.replace(w,item)
else:
    return t

关于python - 一个基本的 python 函数,用于检查替换句子中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31688919/

相关文章:

python 如何使用 imp.find_module 或者替代

python - 如何使用 Matplotlib 从现有轴执行子图

javascript - 使用 jQuery 中 GET 请求的信息通过 Flask 显示转换后的结果

Python 和 PostgreSQL

python - 将 ImageField url 与 django 中的另一个对象关联

python - 如何在matplotlib中绘制三次样条

python - 如果在包根目录中,则无法导入 C++ 扩展

python - 从权限类访问 hyperlinkedRelatedField 对象

python - 在python中处理包含标点编码的数据文件中的字符串

python - 将 Python 类恢复到原始状态