我想在拆分文本时也包含空格,因为我在谷歌上使用导入重新查找
import re
def censor(text,word) :
text1=re.split(r"(s+)",text)
#print text1
sum=""
for i in range(0,len(text1)) :
if text1[i]==word :
for j in range(0,len(word)) :
sum=sum+"*"
else :
sum=sum+text[i]
return sum
我得到的错误是
图像显示错误和代码
如果我包含一个 for 循环来用空格替换每个"e",它不起作用。
在你的代码中,text1
(非常糟糕的命名BTW)是一个单词列表,text
单个字符串。您的第一个for
循环是迭代text1
索引(列表中的单词),但在else
子句中,您将整个text
字符串下标。显然,您希望从单词列表(text1
)中获取单词,而不是text
字符串中位置i
的字符。IOW:将您的else
条款替换为:
sum=sum+text1[i]
并且测试应该通过。
如果您使用正确的命名和正确的代码布局,您肯定会更容易发现问题:
def censor(text, word) :
words = re.split(r"(s+)",text)
sum=""
for i in range(0, len(words)) :
if words[i] == word :
for j in range(0, len(word)) :
sum = sum + "*"
else :
# here you easily spot the error
sum = sum + text[i]
return sum
此外,你正在使事情变得比它们必须的复杂得多。您可以在循环之前一次性预先计算"坏"单词的"替换"字符串(并且您不需要循环来执行此操作),并且您不需要range
和索引访问,ou可以直接迭代单词列表:
def censor(text, word) :
replacement = "*" * len(word)
words = re.split(r"(s+)", text)
cleaned = ""
for w in words :
if w == word :
cleaned += replacement
else :
cleaned += w
return cleaned
还有其他可能的改进,但至少这主要是可读的,而且更具pythonic。