首页 > 解决方案 > 如何使 Python 中的字符串解析变得不那么笨拙?

问题描述

抱歉,如果问题标题太模糊 - 欢迎编辑。

我正在尝试使用 BeautifulSoup 解析 XML,但是因为每个函数调用都可能返回 None,所以我必须在多行上解析单个元素。这很快就会变得笨拙:

books_count = result.books_count

if not books_count:
    return None

books_count = books_count.string

if not books_count:
    return None

books_count = int(books_count)

if not books_count:
    return None

在 Swift 中做同样的事情,这是一种我更熟悉的语言,它更干净:

guard let booksCountString = result.booksCount?.string,
    let booksCountInt = Int(booksCountString) else {
    return nil
}

有没有类似的方法可以在 Python 中做到这一点?我想避免使用 try/catch,因为它可能会在我的代码中不断出现运行时错误,这感觉不是一个好习惯。

标签: pythonstringparsingbeautifulsoup

解决方案


如果您None使用lambda表示您的检查序列,如下所示:

check_1 = lambda r: r.books_count
check_2 = lambda r: r.string
check_3 = lambda r: int(r)

然后我们可以为任意数量的这些检查推广一个解决方案。这个函数(在某种程度上)类似于functools.reduce的工作方式:

def my_reduce(fs, arg, stop_value=None):
    res = arg
    for f in fs:
        res = f(res)
        if res == stop_value:
            return stop_value
    return res

然后像这样使用它:

my_reduce([check_1, check_2, check_3], good_value)
Out[1]: 42

my_reduce([check_1, check_2, check_3], bad_value) is None
Out[2]: True

推荐阅读