在字符串中搜索di中存在的值

2024-09-30 22:16:21 发布

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

正如标题所示,我试图在字符串中的dict中查找值。这与我的帖子有关:Python dictionary - value

我的代码如下:

import mechanize
from bs4 import BeautifulSoup

leaveOut = {
            'a':'cat',
            'b':'dog',
            'c':'werewolf',
            'd':'vampire',
            'e':'nightmare'
            }

br = mechanize.Browser()
r = br.open("http://<a_website_containing_a_list_of_movie_titles/")
html = r.read()
soup = BeautifulSoup(html)
table = soup.find_all('table')[0]

for row in table.find_all('tr'):
    # Find all table data
    for data in row.find_all('td'):
        code_handling_the_assignment_of_movie_title_to_var_movieTitle

        if any(movieTitle.find(leaveOut[c]) < 1 for c in 'abcde'):
            do_this_set_of_instructions
        else:
             pass

如果存储在movieTitle中的字符串包含leaveOutdict中的任何字符串(或者您喜欢的值),我想跳过if块(上面标识为do_this_set_of_instructions)下包含的程序

到目前为止,我对any(movieTitle.find(leaveOut[c]) < 1 for c in 'abcde'):没有什么好运气,因为它总是返回True,而且do\u this\u set\u的指令总是不加考虑地执行。你知道吗

有什么想法吗?你知道吗


Tags: of字符串inimportfortableallfind
1条回答
网友
1楼 · 发布于 2024-09-30 22:16:21

.find()返回-1如果子字符串不在您正在处理的字符串中,那么您的any()调用将返回True如果任何单词不在标题中。你知道吗

您可能需要执行以下操作:

 if any(leaveOut[c] in movieTitle for c in 'abcde'):
     # One of the words was in the title

或者相反:

 if all(leaveOut[c] not in movieTitle for c in 'abcde'):
     # None of the words were in the title

还有,你为什么要用这样的字典?你为什么不把单词储存在一个列表里呢?你知道吗

leave_out = ['dog', 'cat', 'wolf']

...

if all(word not in movieTitle for word in leave_out):
     # None of the words were in the title

相关问题 更多 >