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))].
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:"))
Run the test results:
##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!