如何找出一个单词在一个字符串中重复了多少次?

2024-04-26 17:40:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个程序,要求用户提供一些文本,然后检查单词“owl”在其中重复了多少次。如果这个词包含在另一个词中,这个程序也应该计算这个词。前“hellowl”应该返回;单词“owl”重复了1次。你知道吗

我试过使用.find(),但我收到一条错误消息,如果有人能告诉我如何正确实现它,我将不胜感激。 我当前的代码可以工作,但是如果owl是在上面的例子中提到的另一个单词中说的,则不计算在内

user = str(input("Enter some text: "))

user = user.lower()
user = user.split()

# Counts how many times the word "owl" is said
def owl_count(user):
    count = 0
    for x in user:
        if x == "owl":
            count = count + 1
    return count        

print "There were " + str(owl_count(user)) + " words that contained \"owl\"." 

如果用户输入“I like eatingowls”,则输出应该是“有1个单词包含“owl”,但它返回0


Tags: 代码用户文本程序消息inputcount错误
3条回答

代码有if x == "owl",因此代码只统计等于到“owl”的单词。你知道吗

如果要检查包含“owl”的单词,请改用if "owl" in x。你知道吗

如果使用split,则只有当owl用作单词时,而不是在单词内部时,才会得到匹配。你能做的是

user = str(input("Enter some text: "))
user = user.lower()
# Counts how many times the word "owl" is said
def owl_count(user):
    count = 0
    for x in range(len(user)-2):
        if user[x:x+3] == "owl":
            count = count + 1
    return count        
print("There were " + str(owl_count(user)) + " words that contained \"owl\".")

或者直接使用python的count

def owl_count(user):
    return user.count('owl')   
import re

user = "owlfdfdfowldfdfdowdffowl"

x = user.count("owl")              # Best
y = len(re.findall("owl", user))   
z = len(user.split("owl")) - 1     

print(x, y, z) #3 3 3

相关问题 更多 >