python无法正确地理解我的所有示例

python无法正确地理解我的所有示例,python,Python,为了我自己的理解,我编写了两个函数,并使用我的示例进行测试。类似地,两个函数都有一个正确示例和一个错误示例。 1. 来自单词列表的def计数(tweet,L): “”(str,str列表)->int 第一个参数表示tweet。第二个参数是单词列表。计算列表中的任何单词在tweet中出现的次数,并返回总数 >>> count_from_word_list('I like him and I like her', ["like","her"]) 3 >>> co

为了我自己的理解,我编写了两个函数,并使用我的示例进行测试。类似地,两个函数都有一个正确示例和一个错误示例。 1. 来自单词列表的def计数(tweet,L): “”(str,str列表)->int

第一个参数表示tweet。第二个参数是单词列表。计算列表中的任何单词在tweet中出现的次数,并返回总数

>>> count_from_word_list('I like him and I like her',  ["like","her"])
3
>>> count_from_word_list('I like him and he likes me',  ["like","her"])
1

"""

count = 0
for i in L:
    if i in tweet:
        count = count + 1
return count
二,。 def包含_标签(tweet,h): “(str,str)->bool

第一功能 从您的示例中,我假设第一个函数的主体如下所示

def count_from_word_list(tweet, L):
    count = 0
    for i in L:
        if i in tweet:
            count = count + 1
    return count
让我们按照逻辑步骤思考正在发生的事情:

  • 您可以使用
    i
    迭代要搜索的单词列表
  • 然后使用
    in
    关键字测试
    i
    是否在
    tweet
  • 这就是你的错误所在。python中的
    in
    关键字用于测试某个内容是否包含其他内容。一旦python发现中的
    的左手操作数在右手操作数中,它就会停止,并且不会统计所有出现的外观

    如果要计算给定单词列表在字符串中出现的次数,请执行以下操作:

    def count_occurens_of_words(tweet, word_list):
    # create a variable to hold the count in.
    # It will be incremented each time we find
    # a word in the tweet that contains or matches a
    # word from the word_list
    count = 0
    # for each word in the word_list
    for search_word in word_list:
        # for each word in the tweet
        for word in tweet.split(' '):
            # if a word in the tweet contains or matches a word from the word_list
            if search_word == word:
                # increment count
                count += 1
    # return count           
    return count
    
    输出:

    >>> count_occurens_of_words('I like him and he likes me',  ["like","her"])
    2
    >>> count_occurens_of_words('I like him and he likes her',  ["like","her"])
    3
    >>> 
    
    第二功能 假设您的第二个函数是这样的:

    def contains_hashtag(tweet, h):
        if h in tweet:
            return True
        else:
            return False
    
    你需要做的是检查tweet中是否有你想要的标签。当您在
    中使用
    时,即使hashtag是另一个hashtag的子字符串,它也会返回true。例如

    def contains_hashtag(tweet, h):
        for word in tweet.split(' '):
            if word == h:
                return True
    

    对于第一个函数,实际上下面是我想要显示的:>>>从单词列表(“我喜欢他,我喜欢她”,“喜欢”,“她”])3>>>从单词列表(“我喜欢他,他喜欢我”,“喜欢”,“她”])1中计算,但当我运行它们时,第二个函数分别显示3和2,而不是3和1,我的目标是检查tweet是否包含hashtag,如果hashtag与h相同,则为true。当h不是同一个hashtag或者它只是hashtag的一部分时,它是错误的。例如:我喜欢#csc120(h=#csc120是真的,但h=#csc12是错的,尽管tweet包含了#csc12)@yyang我编辑了我的问题以解决您的担忧。
    def contains_hashtag(tweet, h):
        for word in tweet.split(' '):
            if word == h:
                return True