對我來說,解決這個問題最直接的方法就是使用發電機。
def tokens(filename):
with open(filename) as infile:
for line in infile:
for item in line.split():
yield int(item)
def ballots(tokens):
ballot = []
for t in tokens:
if t:
ballot.append(t)
else:
yield ballot
ballot = []
t = tokens("datafile.txt")
for b in ballots(t):
print b
我看@katrielalex發佈了一個發電機使用解決方案,當我發佈我的。我們之間的區別在於,我使用了兩個獨立的生成器,一個用於文件中的單個令牌,另一個用於您希望解析的特定數據結構。前者作爲參數傳遞給後者,其基本思想是可以爲要分析的每個數據結構編寫一個函數,如ballots()
。您可以對發生器產生的所有內容進行迭代,或者在任一發生器上調用next()
以獲取下一個標記或選票(當您用完時爲StopIteration
例外做準備,或者寫入發生器以生成標記值,例如None
他們用完了真實的數據,並檢查它)。
將整個事物包裝在一個類中是非常簡單的。其實...
class Parser(object):
def __init__(self, filename):
def tokens(filename):
with open(filename) as infile:
for line in infile:
for item in line.split():
yield int(item)
self.tokens = tokens(filename)
def ballots(self):
ballot = []
for t in self.tokens:
if t:
ballot.append(t)
else:
yield ballot
ballot = []
p = Parser("datafile.txt")
for b in p.ballots():
print b
你對BLT格式或擴展(Open STV)格式感興趣嗎?是你給每種格式的唯一規範的鏈接? – 2010-11-11 20:01:14
完全披露,我寫了鏈接維基頁面並設計了擴展格式。我對原始格式非常感興趣,因爲它是獨立於新行的格式(由於我鼓勵人們使用換行符,因此未在wiki頁面中進行說明)。 – 2010-11-11 20:30:17