给定一句英文句子,建立程序数出句子中的单字个数
例: 输入 hello, world!
输出 2
正则切分
text = 'hello ,word!'
# 切分单词
s_res = re.split(r'\W+', text, flags=re.M|re.I)
# 过滤空字符串
f_res = [i for i in s_res if i.strip()]
# 计算个数
print(len(f_res))
有用的话请采纳
t=0
for i in str:
if not ( i>="a" and i<="z" or i>="A" and i<="Z"):
t++
import re
s=input('请输入一句英文:')
a=re.findall(r'[a-zA-Z]+',s)
print(len(a))
用正则实现是最简答的,如果对你有帮助,帮忙采纳下,多谢!
s=input()
word_count=0
same_word=False
for c in s:
if c>='a' and c<='z' or c>='A' and c<='Z':
if not same_word:
word_count+=1
same_word=True
else:
same_word=False
print(word_count)