Python 用于打开XL工作表的嵌套try语句

Python 用于打开XL工作表的嵌套try语句,python,try-catch,xlrd,Python,Try Catch,Xlrd,我正在尝试用XL打开工作表。工作表可以命名为“地图”、“地图”或“地图” 这就是我正在做的 import xlrd book = xlrd.open_workbook(xls) // where xls is the name of the spreadsheet try: sheet = book.sheet_by_name('map') except: try: sheet = book.sheet_by_name('Map') except:

我正在尝试用XL打开工作表。工作表可以命名为“地图”、“地图”或“地图”

这就是我正在做的

import xlrd
book = xlrd.open_workbook(xls) // where xls is the name of the spreadsheet
try:
     sheet = book.sheet_by_name('map')
except:
     try:
        sheet = book.sheet_by_name('Map')
     except:
        try:
          sheet = book.sheet_by_name('MAP')
        except:
           raise

这看起来很笨重。。。有没有一种更像python的方法来实现这一点呢?

只需反复考虑各种可能性,试着依次打开每种可能性:

sheet = None
for thing in ['map','Map','MAP']:
  try:
    sheet = book.sheet_by_name(thing)
    break
  except:
    pass

运行此操作后,
工作表
将设置为可以打开的第一个
对象。如果无法打开任何方法,则
工作表
将是

虽然它的可读性不如其他一些方法,但最短的方法可能是使用:

sheet = book.sheet_by_name(list(set(['map', 'Map', 'MAP']) & set(book.sheet_names())[0])
基本上,这使用了通过另一个SO答案呈现的列表交叉的概念。这可能是一种更简单的创建方法,因此更易于阅读:

possibleNames = ['map', 'Map', 'MAP']
sheetNames = book.sheet_names()
name = intersect(possibleNames, sheetNames)
if len(name) < 1:
    print "Error"
    # break program appropiately
sheet = book.sheet_by_name(name[0])

def intersect(a, b):
    return list(set(a) & set(b))
possibleNames=['map','map','map']
sheetNames=book.sheet_names()
名称=相交(可能的名称、图纸名称)
如果len(名称)<1:
打印“错误”
#适当地中断程序
工作表=书本。工作表按名称(名称[0])
def intersect(a,b):
返回列表(集合(a)和集合(b))

Excel工作表名称不区分大小写。Excel不允许您在一个工作簿中创建多个名称为(地图、地图、地图、地图等)的工作表

candidates = [n for n in book.sheet_names() if n.lower() == 'map']
assert len(candidates) in (0, 1)
if candidates:
     sheet = book.sheet_by_name(candidates[0])
else: 
     whatever()

也许您想提出增强请求,要求Book.sheet by_name使用不区分大小写的搜索。

+1,我正要发布类似的内容,但您击败了我。然而,如果能够明确地处理
事物
都不起作用的情况(OP-re引发最后一个异常),则会很有用-循环中的
else
子句非常适合这种情况。此外,除了:
(与OP中的几个类似名称一样)之外的空白
应该明确提到如果名称错误,
sheet\u by\u name
会引发的特定异常。还有一种可能性是,多个名称可能起作用,例如,可能Map和Map都存在。迭代方法允许您决定覆盖哪个名称。使用
[0]
只需按照
集合所选择的顺序选择它们,而不一定是您想要的顺序。但是,如果您列出了一长串可能的名称,那么
set
方法会更快,并且在其他情况下最好记住这一点。:-)@torek:尝试用2或3个这样的名称在excel中创建工作簿。。。它不会让你这么做的。@JohnMachin:有意思。我实际上并没有使用excel,只是使用类似它的东西,并尝试共享它的一些数据格式。从未测试过它们的区分大小写能力。