Python: 在.FIND()方法中使用AND和OR

1 投票
3 回答
16241 浏览
提问于 2025-04-17 04:51

想象一下,我在解释器里输入了以下代码:

var1 = 'zuuzuu'

然后假设我输入:

var1.find('a')

解释器返回了 -1。我明白这是因为没有找到这个子字符串。但是请帮我理解这个:

var1.find('a' or 'z') #case 1

返回 -1

但是

var1.find('a' and 'z') #case 2

返回 0

根据我脑海中的逻辑,解释器在第二种情况下应该返回 -1,因为子字符串 'a' 和 'z' 都不在这个字符串里。而在第一种情况下,应该返回 0,因为 'z' 是一个子字符串。

谢谢

3 个回答

0

在编程中,有时候我们会遇到一些问题,尤其是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,不知道该怎么解决。比如,有人可能在使用一个特定的功能时,发现它没有按照预期工作,或者出现了错误提示。

这时候,我们可以去一些技术论坛,比如StackOverflow,去寻找答案。在这些论坛上,很多人会分享他们的经验和解决方案,帮助其他人解决类似的问题。

总之,遇到问题时,不要着急,可以先查找一下相关的讨论和解决方案,通常会找到有用的信息。

def count_tokens(text):
   
    #Tokenizes the given text and returns a dictionary with the count of each distinct token.
   
    # First, split the text into individual words
    words = text.split()

    # Next, create an empty dictionary to hold the token counts
    token_counts = {}

    # Loop over the words and count how many times each one appears
    for word in words:
        if word in token_counts:
            token_counts[word] += 1
        else:
            token_counts[word] = 1

    # Finally, return the token counts dictionary
    return token_counts

text = "This is a clock. This is only a clock."
counts = count_tokens(text)
print(counts)


### stopword function
import nltk
from nltk.corpus import stopwords

def count_tokens(text):
   
    #Tokenizes the given text, removes stopwords, and returns a dictionary with the count of each distinct token.

    # First, split the text into individual words
    words = text.split()

    # Next, remove stopwords from the words
    stop_words = set(stopwords.words('english'))
    words = [word for word in words if word.lower() not in stop_words]

    # Next, create an empty dictionary to hold the token counts
    token_counts = {}

    # Loop over the words and count how many times each one appears
    for word in words:
        if word in token_counts:
            token_counts[word] += 1
        else:
            token_counts[word] = 1

    # Finally, return the token counts dictionary
    return token_counts

text = "This is a clock. This is only a clock."
counts = count_tokens(text)
print(counts)
2

这是因为 find 方法实际上不支持 orand,它只支持查找一个字符串。

那么,究竟发生了什么呢?其实,orand 是可以在字符串上使用的运算符。

'a' and 'z' --> 'z'
'a' or 'z'  --> 'a'

所以,简单来说,你就是在正常地搜索 'a''z'

8

表达式 'a' or 'z' 总是返回 'a'。而表达式 'a' and 'z' 总是返回 'z'。这不是一种用于查询容器的特殊语言,而是一个简单的布尔表达式(find 是用它的结果来调用的)。如果你想问“字符串中有没有 'a' 或 'z'”,你需要这样做:

var1.find('a') != -1 or var.find('z') != -1

对于第二个问题(字符串中同时有 'a' 和 'z'):

var1.find('a') != -1 and var.find('z') != -1

撰写回答