[英]Python Data Extraction from Text File
問題是從文本文件中的一堆垃圾中提取數據。 例如,首先,我需要從文本文件中提取此特定部分:
%T 525 1:0.00:6425.12 2:0.01:6231.12 3:0.00:3234.51並持續了很長時間。
然后,我需要專門從每個短語中提取第三個數據,即6425.12、623.12和3234.51,並將其寫入新的文本文件,然后對該數據進行其他一些編輯。
我正在考慮在這種情況下使用正則表達式。 誰能顯示示例代碼? 對於經驗豐富的程序員來說應該很簡單。
您不需要re
獲得數字...
s='%T 525 1:0.00:6425.12 2:0.01:6231.12 3:0.00:3234.51'
columns=s.split()[2:] #Create a list of all the columns except the first 2.
numbers=[c.split(':')[-1] for c in columns] #Split each column on ':' and take the last piece.
但是,在確定如何首先選擇字符串s
之前,我們需要有關文件結構的更多信息。
我認為我不願意使用正則表達式,看起來很簡單。
with open(...) as file:
for line in file:
for word in line.split():
if ':' in word:
print word.split(':')[2] # do something with it here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.