首頁 > 軟體

python如何將txt檔案的內容逐行讀取轉化成陣列

2023-03-27 06:01:28

將txt檔案的內容逐行讀取轉化成陣列

例:

將train5bottle.names的每行內容提取出來轉化成陣列

轉換程式碼:

result = [] 
with open(r'E:HISIdarknet-masterbuilddarknetx64datatrain5bottle.names' ,'r') as f:
    for line in f:
     result.append(line.strip().split(',')[0])  #a.append(b):是將b原封不動的追加到a的末尾上,會改變a的值
        #strip()用於移除字串頭尾指定的字元(預設為空格或者換行符)或字元序列
    print(result) 
print(result[0])

#執行結果:
['0degree', '6degree', '12degree', '18degree', '24degree', '30degree', '36degree', '42degree', '48degree', '54degree', '60degree', '66degree', '72degree', '78degree', '84degree', '90degree', '96degree', '102degree', '108degree', '114degree', '120degree', '126degree', '132degree', '138degree', '144degree', '150degree', '156degree', '162degree', '168degree', '174degree', '180degree']
0degree

將srt檔案轉化成陣列形式

原srt檔案

0
00:00:00,150 --> 00:00:11,430
Fighting this pandemic needs political commitment and commitment at the highest level possible and the President's commitment.

1
00:00:11,431 --> 00:00:16,020
you have what it is in it and the would it have seen it.

2
00:00:16,021 --> 00:00:19,320
and that kind of leadership is very,

3
00:00:19,321 --> 00:00:20,160
very important.

4
00:00:20,161 --> 00:00:21,570
The whole of government approach.

轉化之後的陣列(將時間和內容分離)

['00:00', '00:11', '00:16', '00:19', '00:20']

["Fighting this pandemic needs political commitment and commitment at the highest level possible and the President's commitment.", 'you have what it is in it and the would it have seen it.', 'and that kind of leadership is very,', 'very important.', 'The whole of government approach.']

下面貼出轉化的程式碼,即將cte_test.srt轉化成陣列

之後可以考慮輸送到mysql資料庫上進行復用

count1 = 1
count2 = 2
ktime = []
klrc = []

with open('cte_test.srt', 'r') as f:
    for index, value in enumerate(f.readlines()):
        if index==count1:
            value= value.strip()[3:8]
            ktime.append(value)
            count1=count1+4
        elif index==count2:
            value= value.strip()
            klrc.append(value)
            count2=count2+4

print(ktime)
print(klrc)

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com