Python 程序审查(codecademy)实践中的错误使其变得完美
我想在拆分文本时也包含空格,因为我在google使用的import re上查找到了空格Python 程序审查(codecademy)实践中的错误使其变得完美,python,Python,我想在拆分文本时也包含空格,因为我在google使用的import re上查找到了空格 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)) :
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
此外,你正在使事情变得比必须的复杂得多。在循环之前,您可以一次性预计算“坏”字的“替换”字符串(并且不需要循环来执行此操作),您不需要范围和索引访问,您可以直接在字列表上迭代:
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
还有其他可能的改进,但至少这大部分是可读的,而且更具python风格