我试图将句子中的所有粗话替换成随机字符。我将把它用于我的项目邮件。所以这就是我到目前为止所做的事情。
curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]
filword = ""
flag=0
word = raw_input(">>")
for each in curse:
if each == word:
worlen = len(word)
flag=1
if flag==1:
for c in fil:
if len(filword) != worlen:
filword+= c
word= word.replace(word, filword)
print word
假设列表诅咒中的那些词是粗言秽语。 我已经可以把它翻译成随机字符了。 我的问题是如何从句子中替换犯规词。 例如:
>> Apple you, Ball that car
我希望我的输出是这样的:
!@#$% you, !@#$ that !@#
我该怎么做?谢谢! :)
答案 0 :(得分:1)
curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]
word = raw_input(">>")
words = word.split();
for w in words:
p = w.lower()
if p in curse:
filword=""
worlen = len(w);
for i in range(worlen):
filword += fil[j]
j = (j + 1)%len(fil)
word = word.replace(w,filword);
print word
我首先将该行拆分为一个名为words的列表。现在对于每一个单词,我已经检查过它是否存在于诅咒列表中,如果是,我已经制作了一个长度为单词的填充词。 j =(j +1)%len(fil)是因为worlen可能大于len(fil),在这种情况下你将不得不重用这些字符。 然后终于取代了这个词。
PS:这个代码在汽车,苹果这样的情况下会失败,因为它是基于“”拆分的。在这种情况下,您可以删除除“”之外的所有特殊字符,并将其存储为另一个字符串作为预处理并处理该字符串。
答案 1 :(得分:1)
import re
word2 = re.sub(r'\w+', lambda x: x.group(0).lower() in curse and ''.join(fil[:len(c)]) or x.group(0), word)
print (word2)
>>> '!@#$ you, !@#$ that !@#$'
答案 2 :(得分:0)
如果您不关心每个角色都有自己独特的过滤器替换,您可以使用random.sample
从过滤器中选择任何n个项目,其中n将是单词的长度。因此,考虑到这一点,您可以这样做:
from random import sample
curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]
s = "this apple is awesome like a ball car man"
ns = []
for w in s.split():
ns.append(''.join(sample(fil, len(w)))) if w in curse else ns.append(w)
print(' '.join(ns))
# this ()*!^ is awesome like a %$^& @$^ man