split()表示用空白切割字符,只能切割字符串
e="1 2 4 567 100"
>>> e.split()
['1', '2', '4', '567', '100']
>>> e="1 2 4 \n\r 567 \n 100"
>>> e.split()
['1', '2', '4', '567', '100']# \n\r \n都是制表符不可见字符
#算法思想:把非字母的内容转换为空格;遍历一下字符串把非字母的替换为空格
s="I am a good good baby! You too!"
word_list=s.split() #调试
print(word_list)#调试
new_s=""#作用把切割的单词放进这个字符串,因为字符串无法修改只能拼接
for i in s:
if (i>='a' and i<='z') or (i>='A' and i<='Z'):
new_s+=i
else:
new_s+=""
print(new_s)#调试
print(new_s.split())#调试
print(len(new_s.split()))
#以上封装函数:
def count_word_list(s):
if not isinstance(s,str):
return None
word_list=s.split()
print(word_list) #调试
new_s=""
for i in s:
if (i>='a' and i<='z') or (i>='A' and i<='Z'):
new_s+=i
else:
new_s+=" "
return len(new_s.split())
sentence="I am a good good baby! You too!"
print(count_word_list(sentence))