我需要编写一个函数,该函数接受两个字符串(文本和单词),并将所选单词替换为星号(星号的数量应与被屏蔽单词中字母的数量相对应)。
例如:
如果text="hey hey hey",word="hey",则返回的文本应为:
'*** *** ***'
这是我的代码:
def censor(text,word):
text = text.split(" ")
asterisks=[]
text_with_asterisks=[]
for item in text:
if item not in word:
text_with_asterisks.append(item)
else:
asterisks=[]
for letter in word:
asterisks.append("*")
text_with_asterisks.append(' '.join(asterisks))
return (" ".join(text_with_asterisks))
代码可以运行,但是它返回了以下内容:
*********
并非
*** *** ***.
我使用下面的代码:
return ("_".join(text_with_asterisks))
我得到的是:
'***_***_***'
我不理解为什么“ ”被忽略了,我该如何在单词之间添加空格。
谢谢!
'* * * * * * * * *'
。这是由于text_with_asterisks.append(' '.join(asterisks))
这一行代码导致的。如果我将其中的' '
改为''
,那么我会得到'*** *** ***'
。 - TheBlackCat'*' * len(word)
。 - Peter Woodjoin
两次,第一次用于连接代替每个单词的星号,然后再次用于连接代替星号的单词。虽然你已经做到了,但是你需要在第一次使用""
作为分隔符,下一次使用" "
作为分隔符。 - skykingword
中的单词。调用cencor("he", "hey")
,您将得到***
,因为he
是hey
的一部分,并且三个星号,因为hey
有三个字母。 - skyking