用python的for和if写一个敏感词替换程序
时间: 2023-10-02 07:06:05 浏览: 218
下面是一个使用for和if语句实现的敏感词替换程序示例:
```python
sensitive_words = ["敏感词1", "敏感词2", "敏感词3"] # 敏感词列表
replacement = "***" # 替换字符串
text = input("请输入要替换的文本:")
for word in sensitive_words:
if word in text:
text = text.replace(word, replacement)
print("替换后的文本:", text)
```
在这个例子中,我们使用for循环遍历敏感词列表`sensitive_words`,然后使用if语句判断当前遍历到的敏感词是否在文本中出现。如果出现了,就使用字符串的`replace`方法将敏感词替换为指定的字符串`replacement`。
最后,我们输出替换后的文本。
相关问题
用python写一个敏感词替换程序
下面是一个简单的Python程序,用于将给定的敏感词替换为指定的字符串:
```python
sensitive_words = ["敏感词1", "敏感词2", "敏感词3"] # 敏感词列表
replacement = "***" # 替换字符串
def replace_sensitive_words(text):
for word in sensitive_words:
if word in text:
text = text.replace(word, replacement)
return text
if __name__ == "__main__":
text = input("请输入要替换的文本:")
replaced_text = replace_sensitive_words(text)
print("替换后的文本:", replaced_text)
```
在这个例子中,我们首先定义了一个敏感词列表`sensitive_words`和一个替换字符串`replacement`。然后定义了一个函数`replace_sensitive_words`,它接受一个文本字符串作为参数,然后遍历敏感词列表,如果在文本中找到了敏感词,则将其替换为指定的字符串。
在主程序中,我们使用`input`函数获取用户输入的文本,然后调用`replace_sensitive_words`函数进行替换,最后输出替换后的文本。
python测试用户输入中是否有敏感词,如果有的话就把敏感词替换 为3个星号***。
好的,针对您的问题,您可以使用敏感词库来判断用户输入中是否包含敏感词,如果包含就使用字符串替换方法把敏感词替换为三个星号 "***"。以下是示例代码:
```
sensitive_words = ['敏感词1', '敏感词2', '敏感词3']
input_str = input("请输入要检查的字符串:")
for word in sensitive_words:
if word in input_str:
input_str = input_str.replace(word, '***')
print("替换后的字符串为:", input_str)
```
希望能解决您的问题!
阅读全文
相关推荐
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)