我有一個捕食者及其相應獵物的串列,格式如下:
狼:羊、雞、兔
獅子:斑馬、長頸鹿、瞪羚
并希望將其轉換為這種格式:
狼 羊
狼 雞
狼 兔
獅子 斑馬
獅子 長頸鹿
獅子 瞪羚
到目前為止,我已經嘗試過這段代碼來區分捕食者和獵物
with open('test.txt','r') as in_file:
stripped = (line.strip() for line in in_file)
split = (line.split(":") for line in stripped if line)
pred = []
for line in split:
pred.append(line[0])
with open('test.txt','r') as in_file:
stripped = (line.strip() for line in in_file)
split = (line.split(":") for line in stripped if line)
preys = []
for line in split:
preys.append(line[1])
prey = (line.split(",") for line in preys if line)
但將它們結合起來就是問題所在。我嘗試過類似的方法:
with open('test.txt','r') as in_file:
stripped = (line.strip() for line in in_file)
i=0
while i < line_count:
rows.append(pred[i])
for line in prey:
rows.append(line[0])
i =1
uj5u.com熱心網友回復:
您可以閱讀以下專案:
with open('test.txt','r') as in_file:
dict_predators = {}
for line in in_file:
dict_predators[line.split(':')[0]] = line.split(':')[1].replace('\n', '').split(',')
首先用':'分割行,使用這兩個元素,第一部分作為字典中的鍵,第二部分作為字典中值的串列(我使用替換來擺脫換行符)和然后用','分割將它們變成字串(之前有一個空格,因為你在列印出來時已經要使用一個空格)
您可以將它們寫入這樣的檔案:
with open('test2.txt','w') as in_file:
for k,v in dict_predators.items(): # go through all the elements in the dictionary
for item in v: # go through all the elements of the list of values at that key
in_file.write(f"{k}{item}\n")
uj5u.com熱心網友回復:
如果你可以使用itertools和re模塊,我會選擇類似的東西:
import itertools, re
with open('test.txt','r') as inFile:
with open('test2.txt','w') as outFile:
for line in inFile:
splitted = re.split(":|,", line.strip())
predator = splitted[0]
preys = splitted[1:]
content = zip(itertools.repeat(predator), preys)
outFile.write('\n'.join([ ''.join(item) for item in content ]))
怎么運行的:
- 逐行讀取輸入檔案;
- 對于每一行,它首先
strip是行,然后split是使用colon和comma作為分隔符; - 將捕食者和獵物放在兩個命名變數中,以使代碼清晰;
zip使用和準備內容itertools.repeat;- 為內容中的專案創建一個“已加入”專案串列,使用空字串作為連接符;
- 創建一個字串,以 '\n' 作為連接符連接先前的串列元素;
- 將其寫入 outFile。
注意:可以撰寫一個 with/as 陳述句:
with open('test.txt','r') as inFile, open('test2.txt','w') as outFile:
uj5u.com熱心網友回復:
您可以一次處理一行并將輸出寫入如下:
with open('test.txt') as f_input, open('output.txt', 'w') as f_output:
for line in f_input:
predator, prey = line.split(':')
for p in prey.split(','):
f_output.write(f'{predator} {p.strip()}\n')
給你:
Wolf Sheep
Wolf Chicken
Wolf Rabbit
Lion Zebra
Lion Giraffe
Lion Gazelle
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/423425.html
標籤:
下一篇:嘗試替換缺失資料時出現錯誤堆疊
