Python:用senten中的字符替换脏话

2024-05-13 00:48:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一句话里所有的脏话都换成随机字符。我要用它来邮寄我的项目。这就是我目前所做的。你知道吗

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 !@#

我该怎么做?谢谢!:)


Tags: inyouforlenif字符carword
3条回答
    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 !@#$'
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

我先把这行分成一个叫做单词的列表。现在,每一个单词中的w,我都检查了它是否在诅咒列表中,如果是的话,我就把这个单词的长度做了一个单词。j=(j+1)%len(fil)是因为worlen可以大于len(fil),在这种情况下,必须重用字符。 最后替换了这个词。你知道吗

PS:这个代码在car,apple这样的情况下会失败,因为它是在“”的基础上分裂的。在这种情况下,您可以删除除“”以外的所有特殊字符,并将其存储为另一个字符串作为预处理并处理该字符串。你知道吗

如果您不关心每个字符都有自己唯一的筛选器替换,那么可以使用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

相关问题 更多 >