我写下面的代码来查找输入忽略Python中某些特殊字符的单词的长度
def word_length_list(text):
special_characters = ["'","?"]
for string in special_characters:
clean_text = text.replace(string, "")
count_list = [len(i) for i in clean_text.split()]
print count_list
输出仅接受第一个特殊字符而忽略其余字符。 请在此处说明我的代码有什么问题。
答案 0 :(得分:1)
由于您正在进行多次替换,因此您需要为每次替换更新相同的变量(clean_text
):
def word_length_list(text):
special_characters = ["'","?"]
clean_text = text
for string in special_characters:
clean_text = clean_text.replace(string, "")
count_list = [len(i) for i in clean_text.split()]
print count_list
这样会删除多个特殊字符:
>>> word_length_list("abc def ' ghi ? lmo")
[3, 3, 3, 3]