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

ej83mcc0  于 2023-04-10  发布在  Python
关注(0)|答案(3)|浏览(277)

假设我在解释器中输入以下代码:

var1 = 'zuuzuu'

现在假设我键入:

var1.find('a')

解释器返回-1。我理解这一点,因为子字符串尚未找到。但请帮助我理解这一点:

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

返回-1
但是

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

返回0
根据我头脑中的逻辑,解释器应该在情况2中返回-1,因为子串'a'和'z'不在字符串中。而在情况1中,应该返回0,因为'z'是一个子串。
谢谢

ijnw1ujt

ijnw1ujt1#

表达式'a' or 'z'总是产生'a'。表达式'a' and 'z'总是产生'z'。它不是某种用于在容器中进行查询的DSL,它是一个简单的布尔表达式(并且find被调用其结果)。如果你想说“字符串中是否有'a'或'z'”,你需要做

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

对于第二个(字符串中的'a'和'z'):

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

5t7ly7z52#

这是因为find方法实际上不支持orand,它只支持查询字符串。
那么,到底是怎么回事呢?好吧,原来orand是可以在字符串上执行的运算符。

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

现在你已经知道了,你基本上只是像往常一样搜索'a''z'

s2j5cfk0

s2j5cfk03#

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)

相关问题