我正在学习 Python 并尝试上课。我正在尝试抓取一些网站,这些网站通常有不同的字符串,我用它们来识别我需要的信息。挑战在于,我遇到了可能正在寻找几十个可能的字符串之一的情况。那时我是继续嵌套 if 语句还是创建新类等等。
例如:在下面的类中,我在返回的 html 中查找字符串 x、y 或 z。如果我找到 X,我需要执行一个函数。在 if 语句下面构建该函数是否最有效,或者我可以创建一个新函数并在此类中调用它(即我创建一个名为 x_Found() 的新函数)来解析我需要的数据。
class Link:
def __init__(self, url):
self.url = url
x = 'abc'
y = 'zyx'
z = '123'
def get_html(self):
import urllib2
html = urllib2.urlopen(self.url()).read()
return html
def find_text(self):
html = self.get_html()
if x in html:
run a function called x_found()
elif y in html:
run a different function called y_found()
elif z in html:
run an even different function called z_found()
请您参考如下方法:
Lambda 字典和/或方法指针。
method_map = {'x' : self.x_found, 'y': self.y_found, 'z':self.z_found}
strings_to_search = ['x', 'y', 'z']
for string in strings_to_search:
if string in html:
method_map[string]()
