How to Build a Python Profanity Filter for Game Chat with OOP and Logging
Learn how to create a complete Python profanity‑filter system for game chat, covering a dirty‑word list, string replacement, class‑based player handling, timestamped logging, and interactive user selection, with full source code and step‑by‑step explanations.
This article demonstrates how to implement a profanity‑filter for in‑game chat using Python. It starts by defining a list of prohibited words (the "dirty" list) and shows how to replace any occurrence in a player's message with asterisks using str.replace.
Next, a Player class is introduced to encapsulate player data and behavior. The class includes an __init__ method to store the player's name, a talk method that reads input, replaces profanity, and prints the sanitized message, and a log method that writes the timestamped chat record to a file.
class Player(object):
def __init__(self, name):
self.name = name
self.string = ''
def talk(self):
self.string = raw_input("input-write:")
self.string = self.string.replace('fuck', '*')
# add more replacements as needed
print "公屏显示:%s--%s" % (self.name, self.string)
self.log()
def log(self):
with open('zanghua.txt', 'a') as f:
f.write("{} {}-speak:{}
".format(time, self.name, self.string))The script creates several Player instances (e.g., t1 = Player('white')) and enters an interactive loop where the user selects a player and enters chat messages. The loop uses raw_input to get the player's choice and calls the corresponding talk method. It also demonstrates how to exit the loop.
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 'Invalid input'The article includes sample output screenshots (omitted here) and notes that the log file zanghua.txt must exist beforehand. It also suggests possible extensions such as limiting the number of profanity violations, muting users, or rotating logs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
