文件敏感词替换

class ReplaceFile:
    def replaceFile():
        beReplaced = input('请输入需要被替换的词语:')
        replaced = input('请输入替换的词语:')
        with open(r'C:\Users\Lenovo\Desktop\test.txt','r') as file:
            readFile = file.read()
            newStr = readFile.replace(beReplaced,replaced)
        with open(r'C:\Users\Lenovo\Desktop\test.txt','w') as newFile:
            newFile.write(newStr)
if __name__ == '__main__':
    ReplaceFile.replaceFile()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现评论敏感词替换成*号的功能,可以分为以下几个步骤: 1. 定义敏感词列表 首先,需要定义一个敏感词列表,包含需要过滤的敏感词,可以将这些敏感词存储在数据库或者配置文件,这里以配置文件为例进行说明。 ```properties sensitive.words=政治,色情,暴力 ``` 2. 在后端添加过滤器 在后端,可以使用过滤器来对评论内容进行过滤和替换。具体实现方式如下: ```java public class SensitiveWordFilter implements Filter { private Set<String> sensitiveWords = new HashSet<>(); @Override public void init(FilterConfig filterConfig) throws ServletException { String words = filterConfig.getInitParameter("sensitiveWords"); if (words != null && !words.isEmpty()) { sensitiveWords.addAll(Arrays.asList(words.split(","))); } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; if ("POST".equalsIgnoreCase(httpRequest.getMethod())) { ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(httpRequest); String requestBody = new String(requestWrapper.getContentAsByteArray(), requestWrapper.getCharacterEncoding()); String filteredRequestBody = filterSensitiveWords(requestBody); requestWrapper.setContent(filteredRequestBody.getBytes(requestWrapper.getCharacterEncoding())); } chain.doFilter(request, response); } private String filterSensitiveWords(String content) { for (String sensitiveWord : sensitiveWords) { content = content.replaceAll(sensitiveWord, "***"); } return content; } @Override public void destroy() { } } ``` 上述代码,我们定义了一个过滤器 `SensitiveWordFilter`,该过滤器在 `doFilter` 方法对请求进行拦截,并在其对 POST 请求的请求体进行过滤和替换。具体实现,我们使用了 `ContentCachingRequestWrapper` 类来获取请求体,并使用 `filterSensitiveWords` 方法对敏感词进行过滤和替换。 3. 在前端对评论内容进行过滤和替换 在前端,可以在发送评论请求之前对评论内容进行过滤和替换。具体实现方式如下: ```javascript function filterSensitiveWords(content) { const sensitiveWords = ['政治', '色情', '暴力']; for (const sensitiveWord of sensitiveWords) { content = content.replaceAll(sensitiveWord, '***'); } return content; } function postComment(content) { content = filterSensitiveWords(content); // 发送评论请求 // ... } ``` 上述代码,我们定义了一个函数 `filterSensitiveWords`,该函数使用了 JavaScript 的 `replaceAll` 方法来对敏感词进行过滤和替换。在 `postComment` 函数,我们在发送评论请求之前先对评论内容进行过滤和替换
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值