python - 如何使 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,因为它可能会在我的代码中不断出现运行时错误,这感觉不是一个好习惯。
解决方案
如果您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
推荐阅读
- visual-studio - 如何让 Visual Studio 2017 调用 `yarn start`
- postgresql - 在 Postgres Docker 映像中续集
- c# - 将属性反序列化为 c# 的值
- python - Handing in my application, along with its virtual environment
- python - 如何检查数组中是否存在类的属性?
- python - 如何在 3D 条件下在画布上显示 tkinter 多边形?
- php - 通过循环将数组值插入mysql
- javascript - 您如何在 localhost 中呈现 Google 广告单元?
- wordpress - Wordpress 不允许我更改 slug
- ms-access - 如何循环遍历记录集并根据记录集更新表字段值?