2017-02-15 123 views
0

我有一個文本文件,我試圖從中提取列和數據。以下是數據的一個樣本:使用python將字段添加到文本文件中的列

-Global stats enabled 
Cpu Utilization : 0.1 % 45.4 Gb/core 
Platform_factor : 1.0 
Total-Tx  :  270.75 Mbps 
Total-Rx  :  0.00 bps 
Total-PPS  :  37.98 Kpps 
Total-CPS  :  0.00 cps 

Expected-PPS :  102.71 Kpps 
Expected-CPS :  2.78 Kcps 
Expected-BPS :  764.51 Mbps 

Active-flows :  366 Clients :  252 Socket-util : 0.0023 %  
Open-flows  :  2792 Servers : 65534 Socket :  366 Socket/Clients : 1.5 
drop-rate  :  270.75 Mbps 
current time : 7.6 sec 
test duration : 3592.4 sec 

-Latency stats enabled 
Cpu Utilization : 0.0 % 
if| tx_ok , rx_ok , rx check ,error,  latency (usec) , Jitter   max window 
    |   ,  ,   ,  , average , max , (usec)      
---------------------------------------------------------------------------------------------------------------- 
0 |  1116,  0,   0, 0,   0 ,  0,  0  | 0 0 0 0 0 0 0 0 0 0 0 0 0 
1 |  1116,  0,   0, 0,   0 ,  0,  0  | 0 0 0 0 0 0 0 0 0 0 0 0 0 
2 |  1116,  0,   0, 0,   0 ,  0,  0  | 0 0 0 0 0 0 0 0 0 0 0 0 0 
3 |  1116,  0,   0, 0,   0 ,  0,  0  | 0 0 0 0 0 0 0 0 0 0 0 0 0 
[2J[2H 
-Per port stats table 
     ports |    0 |    1 |    2 |    3 
----------------------------------------------------------------------------------------- 
    opackets |   30391 |   48748 |   30360 |   48696 
    obytes |   2468147 |  68386300 |   2465677 |  68310324 
    ipackets |    0 |    0 |    0 |    0 
    ibytes |    0 |    0 |    0 |    0 
    ierrors |    0 |    0 |    0 |    0 
    oerrors |    0 |    0 |    0 |    0 
     Tx Bw |  4.77 Mbps |  130.69 Mbps |  4.76 Mbps |  130.53 Mbps 

我需要創建項目等共計-TX,下降率等列...然後對這些每次迭代添加值,進入一個新的行。

目前我可以提取列,不過需要幫助的相關數據的行添加到CSV文件:

import csv 
import itertools 

with open('output.txt', 'r') as in_file: 
    stripped = (line.strip() for line in in_file) 
    lines = (line for line in stripped if line) 
    grouped = itertools.izip(*[lines] * 4) 
    with open('output_stats.csv', 'w') as out_file: 
     writer = csv.writer(out_file) 
     writer.writerow(('current time', 'drop-rate', 'Total-Tx', 'Total-Rx')) 
     writer.writerows(grouped) 

回答

0

你想解析和條目保存在-Global stats enabled節?

使用regex也許矯枉過正,我建議你使用一些基本的字符串split

對於只有一個冒號:它(你可以使用str.count),使用split(:)會給兩個項目的列表,左側鍵和右側的值。

對於線與多個線路結腸,你可以先用冒號和空格分開,要特別注意在Socket-util%,它會給[key1, value1, key2, value2, ...]列表(可能需要扁平化的列表,請參閱Making a flat list out of list of lists in Python)。

然後,你可以寫鍵作爲列名稱及其相應的值。

如果您還想解析並存儲-Latency stats enabled部分中的ASCII表,則可以嘗試使用pandas,請參閱How to create a Pandas DataFrame from String

+0

是的,在這一點上,我只需要存儲包含':' 的行的條目,這樣我就可以使用'split(:)'謝謝你,會試試這個 –

相關問題