您好,登錄后才能下訂單哦!
本篇內容主要講解“python怎么將txt文件的內容逐行讀取轉化成數組”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“python怎么將txt文件的內容逐行讀取轉化成數組”吧!
例:
將train5bottle.names的每行內容提取出來轉化成數組
轉換代碼:
result = [] with open(r'E:\HISI\darknet-master\build\darknet\x64\data\train5bottle.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文件
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)
到此,相信大家對“python怎么將txt文件的內容逐行讀取轉化成數組”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。