Show me the code之Python练习册 Q11~12 关键词过滤

本文介绍了一种基于Python的文本过滤方法,通过读取敏感词列表并检查用户输入,实现敏感词的检测与替换功能。当检测到敏感词时,会使用星号进行替换,以保护言论合规性。

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

"""
    问题:敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
"""

def filterwords():
    words = []
    f = open('d://filtered_words.txt', 'rb')
    for l in f.readlines():
        words.append(l.decode('utf-8'))

    iw = input('enter your words: ')
    for w in range(len(words)):
        if iw.find(words[w].strip()) > -1:
            print('Freedom')
        else:
            print('Human Rights')

if __name__ == '__main__':
    filterwords()
"""
    问题:敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当
        用户输入敏感词语,则用 星号 * 替换,
        例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
"""
def filterwords(iw):
    words =[]
    file = open('d://filtered_words.txt', 'rb')
    for f in file.readlines():
        words.append(f.decode('utf-8'))

    for i in range(len(words)):
        word = words[i].strip()
        if iw.find(word) > -1:
            return word
    return ''

def main():
    iw = input('enter your words: ')
    word = filterwords(iw)
    if word != '':
        print(iw.replace(word, '***'))
    else:
        print(iw)

if __name__ == '__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值