• 技术文章 >Python技术 >Python基础教程

    python敏感词替换

    小妮浅浅小妮浅浅2021-04-25 10:09:44原创9748

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    1、替换过程

    (1)open()文件迭代器,读取文件的每行,不过这个会自动在读取的对象后面增加一个跨行符号\n

    (2)判断是否有敏感词。in成员测试in

    (3)将敏感词替换成***

    2、实例

    敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights
    '''
    def filtered_words():
        user_words = input('Please input your words:')
        for f in open('E:/Users/summer/PycharmProjects/untitled/filtered_words.txt'):
            #open()文件迭代器,读取文件的每行,不过这个会自动在读取的对象后面增加一个跨行符号\n
            if f.rstrip() in user_words:#rstrip()可以去掉右边的跨行符
                #判断是否有敏感词。in成员测试in
                print('Freedom')
                break
        else:
            print('Human Rights')
     
    if __name__ == '__main__':
        filtered_words()
    '''
    # 将上述的敏感词替换成***
    def filtered_words():
        user_words = input('Please input your words:')
        for f in open('E:/Users/summer/PycharmProjects/untitled/filtered_words.txt'):
            #open()文件迭代器,读取文件的每行,不过这个会自动在读取的对象后面增加一个跨行符号\n
            fw = f.rstrip()#rstrip()可以去掉右边的跨行符
            if fw in user_words:#判断是否有敏感词。in成员测试in
                f = len(fw)
                user_input = user_words.replace (fw,'***'*f)
     
        else:
            print(user_input)
     
    if __name__ == '__main__':
        filtered_words()

    以上就是python敏感词替换的方法,一般来说我们是把敏感词换成星号的替换形式的。大家在处理文本有敏感词时,不妨尝试这种方法。更多Python学习指路:python基础教程

    专题推荐:python 敏感词
    品易云
    上一篇:python异常处理关键字 下一篇:python三位数反序输出

    相关文章推荐

    • python删除元素的使用条件• python列表排序的两种方式• python for…in循环的使用• python处理数字列表的函数• python切片如何进行索引• python中用切片复制列表• python字典中键值对的操作• python使用items()遍历键值对• python函数如何指定默认值• python函数中返回值的作用• python在函数中传递实参• python使用import导入导出• python使用as指定别名• python编写函数的注意点• python类属性设置默认值

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网