创建一个函数,该函数计算确切单词在字符串中出现的时间 [英] Create a function that counts number of time the exact word occurs in string

查看:36
本文介绍了创建一个函数,该函数计算确切单词在字符串中出现的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我是python的新手,正在尝试创建一个函数,该函数计算确切单词在字符串中出现的时间.这是我的python代码:

well, I'm new to python and trying to Create a function that counts number of time the exact word occurs in string. this is my python code :

def fsi(s):
    count = 0
    for word in s.lower().split():
        if word == 'ali':
            count += 1
        return count 

当我调用fsi函数时,它无法正常工作,并且返回的数字不正确.它不再返回1

when i call fsi function it doesn't work properly and the returned number isn't correct. it just returns 1 not anymore

fsi('ali and ali and ali!')

您对我提出什么解决方案?

what do you propose me to fix it ?

推荐答案

正确的方式1:

import re
len(re.findall(pattern, string_to_search))
#Usage 
len(re.findall('\bali\b', s))

正确的方式2:

s = "ali and ali and ali!"
s.count('ali')

这篇关于创建一个函数,该函数计算确切单词在字符串中出现的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆