# (15分)
# 1.返回一个字符串中出现次数最多的单词
# 2.字符串中可能有英文单词、标点、空格
def max_count_word(s):
n = 0 #记录下标
lt = [] #定义列表,存取数据
for i in range(len(s) - 1): #遍历字符串
if(not ((ord(s[i]) >= 97 and ord(s[i]) <= 122) or (ord(s[i]) >= 65 and ord(s[i]) <= 90))):#判断是否英文字母
if i > n: #防止出现连续不是英文字母的情况
lt.append(s[n:i]) #当出现非英文字母时,截取字符串进入列表
n = i + 1 #更新下标值
if ((ord(s[-1]) >= 97 and ord(s[-1]) <= 122) or (ord(s[-1]) >= 65 and ord(s[-1]) <= 90)):#判断字符串的结尾是否写标点
lt.append(s[n:]) #如果最后没写标点的话,应加上最后的单词
for j in range(len(lt) - 1): #遍历,根据字符串出现的次数进行从大到小的排序
for k in range(len(lt) - j - 1):
if(lt.count(lt[k]) < lt.count(lt[k + 1])):
t = lt[k]
lt[k] = lt[k + 1]
lt[k + 1] = t
return lt[0] #返回lt[0],即为最多出现的单词
#若需要返回出现次数第二多的单词
#return lt[lt.count(lt[0])]
#测试代码
s = 'You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.'
print(max_count_word(s))
Python 返回一句话中出现次数最多的单词
最新推荐文章于 2023-04-12 17:25:16 发布