我有稱爲宋一個對象,作爲被定義爲變量的引用:遍歷在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