我有一個 .txt 檔案,上面用大寫字母寫著“NAMES”、“POINTS”和“SUMMARY”,每個字母后跟包含資料的行。這三個組中的每一個都由一個空行分隔:
NAMES
John Cena
Sam Smith
Selena Gomez
POINTS
sixteen
forty
thirty
SUMMARY
eighth place
sixth place
first place
我的目標是創建三組獨立的名稱、要點和摘要。
我已經使用以下代碼創建了一組名稱(按預期輸出一組所有名稱):
names = set()
for line in open('handout_example.txt'):
line = line.strip()
if not line:
break
names.add(line)
names.remove('NAMES')
print(names) #this outputs a set of all names
但是,我不確定如何創建一組點和一組摘要,因為它們位于空行之后而不是與名稱不同的代碼開頭。任何幫助將不勝感激!!提前謝謝你 <3
uj5u.com熱心網友回復:
這是我的解決方案:
names = set()
points = set()
summary = set()
next = 0
for line in open('handout_example.txt'):
line = line.strip()
if not line:
next = 1
continue
if next == 0:
names.add(line)
elif next == 1:
points.add(line)
elif next == 2:
summary.add(line)
names.remove('NAMES')
points.remove('POINTS')
summary.remove('SUMMARY')
print(f'{names}\t{points}\t{summary}')
它很簡單,可以做得更好,但我想這對你有用。
編輯:更“漂亮”的版本:
nps = dict({'names': set(), 'points': set(), 'summary': set()})
nps_n = ['names', 'points', 'summary']
next = 0
for line in open('handout_example.txt'):
line = line.strip()
if not line:
next = 1
continue
nps[nps[next]].append(line)
uj5u.com熱心網友回復:
我會嘗試檢測您是否看到空行或標題行,以便您選擇合適的型別。例如:
data_types = {"NAMES":set(), "POINTS":set(), "SUMMARY":set()}
current_key = None
然后在回圈中,檢查該行是否與其中一種資料型別匹配(并且不是空行)。如果是,則將 current_key 設定為該值并添加到字典中正確位置的集合中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535625.html
標籤:Python文件放
上一篇:從文本檔案創建二維陣列
下一篇:在Tcl中寫入檔案會產生額外的行
