我有称为宋一个对象,作为被定义为变量的引用:遍历在Python
class Song(object):
def __init__(self):
self.title = None
self.songauthor = None
self.textauthor = None
self.categories = None
这个类里面我有解析该对象的运行时性能的方法,“元数据” ,它基本上只是一个带有一些格式化文本的文本文件,我用正则表达式解析。在这个过程中,我想出了下面的代码,我相当肯定可以简化为一个循环。
re_title = re.compile("^title:(.*)$", re.MULTILINE)
re_textauthor = re.compile("^textauthor:(.*)$", re.MULTILINE)
re_songauthor = re.compile("^songauthor:(.*)$", re.MULTILINE)
re_categories = re.compile("^categories:(.*)$", re.MULTILINE)
#
# it must be possible to simplify the below code to a loop...
#
tmp = re_title.findall(self.metadata)
self.title = tmp[0] if len(tmp) > 0 else None
tmp = re_textauthor.findall(self.metadata)
self.textauthor = tmp[0] if len(tmp) > 0 else None
tmp = re_songauthor.findall(self.metadata)
self.songauthor = tmp[0] if len(tmp) > 0 else None
tmp = re_categories.findall(self.metadata)
self.categories = tmp[0] if len(tmp) > 0 else None
我猜测这可以通过封装参考性质(例如self.title),并在数据类型(可能元组)对应的正则表达式(re_title)来完成,然后遍历列表这些数据类型。
我有一个尝试使用一个元组这样:
for x in ((self.title, re_title),
(self.textauthor, re_textauthor),
(self.songauthor, re_songauthor),
(self.categories, re_categories)):
data = x[1].findall(self.metadata)
x[0] = data[0] if len(data) > 0 else None
这可怕的失败,因为我不能修改在运行时的元组。任何人都可以提供一个关于我如何解决这个问题的建议吗?
如果你只对第一场比赛感兴趣,你为什么要用'findall'? – 2014-11-21 22:21:58
@MarkRansom懒惰。 – v3gard 2014-11-21 22:50:46