我需要编写一个函数,它接受两个字符串(文本和单词),并返回所选单词替换为星号的文本(星号的数量应该对应于被审查的单词中的字母数)。
例如:
如果text=“嘿嘿”和word=“嘿嘿”,返回的文本应该是:
'*** *** ***'这是我的代码:
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))相反,我得到了:
'***_***_***'我不明白为什么“”会被忽略,以及如何在单词之间添加一个空格。
谢谢!
发布于 2015-08-25 09:32:20
当你加入星号时,你有一个额外的空间:
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)) #here's the culprit
return (" ".join(text_with_asterisks))censor("hey hey hey", "hey")输出您想要的东西('*** *** ***')
我只是指出了你的错误,但肯定有一个更优雅和更有效的方式来做你想做的事。
发布于 2015-08-25 09:32:19
以下是最简单的解决方案
text.replace(word, "*" * len(word))发布于 2015-08-25 09:39:59
做这件事的方法-
import re
def censor(text,word):
return re.sub(r'\b(?i){0}\b'.format(re.escape(word)),'*' * len(word), text)示例/演示-
>>> censor('hey hey they hey','hey')
'*** *** they ***'
>>> censor('hey hey they Hey','hey')
'*** *** they ***'https://stackoverflow.com/questions/32200262
复制相似问题