Python writes the principle of blocking swear words in major chat systems

高洛峰
Release: 2016-12-01 15:38:07
Original
1190 people have browsed it

Python writes the principle of blocking swear words in major chat systems

I suddenly thought of a video in which the barrage was harmoniously filled with * signs on the screen. I thought it was very interesting, and then I wanted to try using Python to write it, and it turned out to be really fun. It has some effect. The idea is that first of all, you have to have a warehouse where swear words are stored so that they can be detected later. Then I personally like to use lists, because lists are easy to use and expand flexibly. With the swear words library, we are now thinking about how to block swear words in the core. You have to remember what the data type of the barrage input by the player is. The first file is followed by a string. If there are no special requirements, just use it. There are always these data structures among them. With the string, it is easy to replace the * sign and so on. A lot, right? What we are talking about today is a complete set of structures. In order to let everyone learn it more clearly, I will split the code and then assemble it to talk about it, so that everyone will have a deeper understanding. First, let’s take a look at the core functions. The code to replace the swear words is as follows:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import datetime
time = datetime.datetime.now()

speak = '你个狗日的,fuckR你妈哟,操你个仙人板板,个老麻批'
dirty = ['fuck','狗日的','犊子','麻批','仙人板板','R你妈','操你','草你']

for i in dirty:
    speak = speak.replace(i,'*')
print speak+" | "+str(time)
Copy after login

Python writes the principle of blocking swear words in major chat systems

Is it simple and easy to block the swear words? This imports the time module datetime to get the current local time, which will be used to write logs and save them later. Of course, many games The current time will also be displayed in the dialogue, and then speak is the curse word that the player wants to output (now it is a demonstration and will be changed to Input for real input interaction), and dirty is the defined curse word library (of course I didn’t write too much because each region is so different. (can’t finish writing), followed by a for loop to retrieve. As long as what you say contains curse words, we will replace them with replace. The final printing will mean that all the subtitles displayed on the public screen are *... Of course, we also need to think about how to track who said what at what time. In this way, classes must be used for association. There will definitely be doubts about why classes are used. First of all, classes are one type (for example, tables include square tables, round tables, and conference tables). Table, office desk, etc.) summary of the description of things, such as a group of players Player, they all have their own game names, and then they all have chat functions (we also call them actions), so that they can both classify and differentiate. . The code is as follows:

class Player(object):

    def __init__(self,name):
        self.name = name

    def talk(self):
        self.string = 'whatever fuck no joke'
        self.log()
        self.string = self.string.replace('fuck','雅蠛蝶')
        print "公屏显示:%s--%s"%(self.name,self.string) 

    def log(self):
        print "日志记录为:%s--%s"%(self.name,self.string)

t1 = Player('white')
t1.talk()
Copy after login

Python writes the principle of blocking swear words in major chat systems

Here is a comprehensive introduction to the use of classes and workflow effects. Here we first create a player class like Player, and init initializes his name, which has the chat function talk and logs. Record function, then let’s talk about the chat operation process. Each player will have a game name after registering and logging into the game (you can understand it as after logging into QQ). Here self.name=name is equal to getting your personal name (screen name), and then Open the chat window to enter talk, self.string the chat information you entered, self.log records the log, the focus is to first record your original words in the chat log so that your record can be found, replace it with self.string.replace If you say dirty words, then only the replaced words will be displayed on the screen. For example, what was printed was originally fuck programmed by Ya Zhudie... Is this workflow very clear? Of course, if you don't understand the class method, it will be very confusing here. I'm confused, take your time, as long as you have this idea and learn the class, it will be very easy. Of course it won’t end like this. Finally, the basic complete code is released. The code is as follows:

import datetime

time = str(datetime.datetime.now())[:-7]

dirty = ['fuck','狗日的','犊子','麻批','仙人板板','R你妈','操你','草你']

class Player(object):

    def __init__(self,name):
        self.name = name

    def talk(self):
        self.string = raw_input("input-write:")
        # self.string = '你个狗日的,R你妈哟,操你个仙人板板,个老麻批'
        self.log()
        for i in dirty:
            self.string = self.string.replace(i,'雅蠛蝶')
        print "{}  {}-speak:{}".format(time,self.name,self.string,)

    def log(self):
        with open('zanghua.txt','a') as f:
            f.write("{}  {}-speak:{}\n".format(time,self.name,self.string))


t1 = Player('white')
t2 = Player('black')
t3 = Player('green')
while True:
    n = raw_input('change Player:')
    if n == '1':
        t1.talk()
    elif n == '2':
        t2.talk()
    elif n == '3':
        t3.talk()
    elif n == 'q':
        print 'Bye'
        break
    else:
        print "尼玛在逗我?"
Copy after login

The test results are as follows:

Python writes the principle of blocking swear words in major chat systems

Python writes the principle of blocking swear words in major chat systems

You can create a new file named zanghua.txt with empty text, just for Demonstrates the behavior effect of storing logs. The above print says that change Player is a simple switch to demonstrate different user inputs. In fact, in the system, you rarely switch users after logging in. It is just chatting with the current account. The code here is Add the file processing method with open (file name, open mode), call it f or something like that, and then write write (remember to add n newline character at the end of writing, otherwise it will be difficult to read the first line in full) About datetime[: 7] Slicing is more concise by ignoring the remainder after the time when printing above. The basic process is this. Of course, there can be many extensions, such as prohibiting speech after a certain number of swear words, limiting speech to a few minutes, logs can be cleared regularly, etc. It’s up to you to research it yourself. The amount of code is a bit large and I won’t show it here. The last picture I want to explain is as follows. Many people may have misunderstood something. .

Python writes the principle of blocking swear words in major chat systems


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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template