循环输入并查看i中的发生情况

2024-04-20 08:49:23 发布

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

我试图计算用户在回复开始时输入http://url的次数,或者在tweet之前输入空格或结尾的次数 问题是,无论我在tweet中输入什么,它总是保持在0,即使它的垃圾邮件http://it仍然保持在0

def count_url(tweet):
count = 0
for word in tweet:
    if word.startswith('http://') or word.endswith('http://'):
        count = count + 1
return count

Tags: 用户inhttpurlforifdefcount
1条回答
网友
1楼 · 发布于 2024-04-20 08:49:23

您正在函数中输入tweets,它们是字符串。所以,如果你有一条推特,比如:

"I love potatoes, buy some here http://potatoesarethebest.com"

然后迭代,你在迭代字符,而不是单词。您需要做的是字符串拆分为列表,方法是调用该字符串上的split方法,默认情况下,该方法将拆分为空格:

>>> s = "I love potatoes, buy some here http://potatoesarethebest.com"
>>> s.split()
['I', 'love', 'potatoes,', 'buy', 'some', 'here', 'http://potatoesarethebest.com']

这意味着在函数中,当在tweet上迭代时,只需调用split()。此外,您可以简单地使用count += 1而不是count = count + 1

使用此方法,使用word.endswith('http://')也没有意义endswith查找字符串中以匹配结尾的部分。因此,您正在寻找类似“thisishttp://”的内容。这没有多大意义

def count_url(tweet):
    count = 0
    for word in tweet.split():
        if word.startswith('http://'):
            count += 1
    return count

演示:

>>> res = count_url("I love potatoes, buy some here http://potatoesarethebest.com")
>>> print(res)
1

此解决方案的限制是,如果您有以下字符串,则它将无法工作:

"this is awesome check here:http://www.stuff.com"

您还必须注意其他一些限制。因此,您还需要知道您希望使用什么样的确切标准来执行匹配

相关问题 更多 >