python小程序-0010

本文介绍了一个使用Python实现的敏感词过滤程序,该程序通过读取包含敏感词汇的文本文件,并利用命令行接口让用户输入文本,如果输入的文本中包含敏感词汇,则会用星号进行替换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第10题:敏感词文本文件 filtered_words.txt,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。

#!/usr/bin/env python3
# -*- coding : utf-8 -*-

import cmd
import sys

class words(cmd.Cmd):
    def __init__(self,path):
        self.path = path
        self.filterwords = []
        cmd.Cmd.__init__(self,self.path)
        with open(self.path,'r') as f:
            for line in f.readlines():
                line = line.strip('\n')
                self.filterwords.append(line)
        self.intro = "Please enter your words:"
        self.prompt = "> "

    def default(self,word):
        #print( self.filterwords)
        for i in self.filterwords:
            word = word.replace(i,len(i)*'*')
        print(word)

    def do_exit(self,arg):
        sys.exit()

if __name__ == "__main__":
    path = input("Please input filter_words_text path:")
    cc = words(path)
    cc.cmdloop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值