繁体   English   中英

Python:用句子中的字符替换脏话

[英]Python: Replacing foul words with characters from a sentence

我正在尝试将句子中的所有粗俗单词替换为随机字符。 我将在我的项目Mailing中使用它。 所以这是我到目前为止所做的。

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

我怎样才能做到这一点? 谢谢! :)

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:此代码在汽车,苹果等情况下将失败,因为它是基于“”拆分的。 在这种情况下,您可以删除除“”以外的所有特殊字符,并将其存储为另一个字符串作为预处理并对该字符串进行处理。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM