2020年2月-------字符串(统计)
1、统计一句话有多少个单词
方法一:
s = "I am a good boy"
m=s.split()
count=0
result=[]
for i in m:
if i not in result:
count+=1
print(count)
执行结果:
>>> print(count)
5
>>>
方法二
s = "I am& a good, boy 123 @!23 ab@"
先要去除特殊符号
import string
def func(s):
for c in s:
if c in string.punctuation:
s=s.replace(c,"")
m=s.split()
result=[]
for i in m:
if i.isalpha():
result.append(i)
print(result)
return len(result)
s = "I am& a good,boy 123 @!23 ab@"
func(s)
执行结果:
>>> func(s)
['I', 'am', 'a', 'good', 'boy', 'ab']
6
方法三:
import re
s = "I am a good, boy 123 @!23 ab@"
word_list=re.findall(r"\b[A-Za-z]+\b",s)
print(word_list)
执行结果:
>>> import re
>>> s = "I am a good, boy 123 @!23 ab@"
>>> word_list=re.findall(r"\b[A-Za-z]+\b",s)
>>> print(word_list)
['I', 'am', 'a', 'good', 'boy', 'ab']
>>> print(len(word_list))
6
>>>
25、统计一句话中不重复出现的单词数量。不能用set方法
方法一
import string
def func(s):
for c in s:
if c in string.punctuation:
s=s.replace(c,"")
m=s.split()
result=[]
for i in m:
if i.isalpha() and m.count(i)==1:
result.append(i)
print(result)
return len(result)
s = "I am& a good, good boy,boy,123 123 @!23 ab@"
func(s)
执行结果:
>>> s = "I am& a good, good boy,boy,123 123 @!23 ab@"
>>> func(s)
['I', 'am', 'a', 'ab']
4
26、输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数,面试概率极高的题目
def func(s):
alpha_num=0
space_num=0
str_num=0
other_num=0
for i in s:
if i.isalpha():
alpha_num+=1
elif i.isspace():
space_num+=1
elif i in "0123456789":
str_num+=1
else:
other_num+=1
return alpha_num,space_num,str_num,other_num
s = "I am& a good, good boy,boy,123 123 @!23 ab@"
func(s)
>>> func(s)
(20, 8, 8, 7)
>>>

浙公网安备 33010602011771号