我有一個名為的文本檔案file.txt
,如下所示:
0, 1, 2. |classes
A0: 1, 2, 3
A1: 1, 2, 3
A2: 1, 2, 3
A3: 1, 2, 3, 4
| Final Pseudo Deletion Count is 0. Optimisaiton not possible.
從這個檔案中,我只想取出屬性名稱:A0、A1、A2、A3。我該怎么做?
我的意思是對于這個特定的檔案,它A0,A1,A2,A3只是但我想要一般檔案的輸出。可以有A0,A1.....An。像下面這樣:
0, 1, 2. |classes
A0: 1, 2, 3
A1: 1, 2, 3
A2: 1, 2, 3
A3: 1, 2, 3, 4
A4: 1, 2, 3
A5: 1, 2, 3, 4
| Final Pseudo Deletion Count is 0. Optimisaiton not possible.
所以在這種情況下,輸出將包含A0, A1, A2, A3, A4, A5.
我試過:
f = open('filename1.txt')
attrib1 = f.readline()
attrib = []
for i in range(1, len(attrib1)-1):
v_pos_colon = attrib1[i].find(':')
attrib.append(attrib[i][0:v_pos_colon])
print(attrib)
uj5u.com熱心網友回復:
您正在遍歷檔案第一行中的字符,而不是遍歷檔案的行。
find()-1找不到字串時回傳。因此,當:該行中沒有 no時,您將添加 slice attrib[i][0:-1],它將所有內容切成倒數第二個字符。您應該首先測驗是否找到了該字符。
attrib = []
with open('filename1.txt') as f:
for line in f:
if ':' in line:
attrib.append(line.split(':')[0])
print(attrib)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/326721.html
上一篇:迭代串列時減去的值有隨機錯誤計算
