0

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

我的代码如下所示:

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

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

到目前为止,我没有运气,any(movieTitle.find(leaveOut[c]) < 1 for c in 'abcde'):因为它总是返回 True 并且 do_this_set_of_instructions 无论如何都会执行。

有任何想法吗?

4

1 回答 1

1

.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
于 2013-06-11T20:40:39.180 回答