How to implement sensitive word replacement in Python

coldplay.xixi
Release: 2020-10-23 14:38:43
Original
17893 people have browsed it

Python’s method of replacing sensitive words: first pour in the sensitive word text; then when the user inputs a sensitive word that matches successfully, replace it with [*], the code is [new_string = string.replace(words,"* "*len(words))].

How to implement sensitive word replacement in Python

Python method to implement sensitive word replacement:

Ideas

This question is practiced It is a string replacement, but if you are not careful, it is easy to think of the process as simple. The process will involve the use of recursive methods. Using python2 under Windows also involves encoding conversion. What should be considered is that after filtering the string once, the filtering may not be completed. For example, after filtering once and removing sensitive characters After string replacement, sensitive words are newly formed in the remaining string. This situation must be solved by recursion. The replacement can be considered completed until the result after filtering and replacing is the same as before filtering. Otherwise, there will be an omission in the logic.

Write the script

The code is as follows:

# -*- coding: utf-8 -*- import os curr_dir = os.path.dirname(os.path.abspath(__file__)) filtered_words_txt_path = os.path.join(curr_dir,'filtered_words.txt') import chardet def filter_replace(string): string = string.decode("gbk") filtered_words = [] with open(filtered_words_txt_path) as filtered_words_txt: lines = filtered_words_txt.readlines() for line in lines: filtered_words.append(line.strip().decode("gbk")) print replace(filtered_words, string) def replace(filtered_words,string): new_string = string for words in filtered_words: if words in string: new_string = string.replace(words,"*"*len(words)) if new_string == string: return new_string else: return replace(filtered_words,new_string) if __name__ == '__main__': filter_replace(raw_input("Type:"))
Copy after login

Run the test results:

How to implement sensitive word replacement in Python

##Related Free learning recommendations:python tutorial(video)

The above is the detailed content of How to implement sensitive word replacement in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!