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

时间:2013-06-11 20:35:29

标签: python

正如标题所示,我试图在字符串中的字典中查找值。这与我的帖子有关: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

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

到目前为止,我对any(movieTitle.find(leaveOut[c]) < 1 for c in 'abcde'):没有好运,因为它始终返回True,而do_this_set_of_instructions总是执行。

有什么想法吗?

1 个答案:

答案 0 :(得分: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