在python matplotlib中读取文本文件和显示数据

时间:2017-06-04 06:01:51

标签: python csv matplotlib defaultdict

我曾尝试使用python csv读取txt文件,然后使用python matplotlib在图表中显示

文本文件中的简单数据:

261 P 0.18 0 834 64627 0 768 0 320 834 64627 0 768 0 320 (radio 1.17% / 1.17% tx 0.00% / 0.00% listen 1.17% / 1.17%)

和这个用于读取文件的python脚本但它不起作用且没有错误消息。

import csv
import matplotlib.pyplot as plt

# for P lines
#0-> str,
#1 -> clock_time(),2-> P, 3->rimeaddr_node_addr.u8[0],rimeaddr_node_addr.u8[1], 4-> seqno,
#5 -> all_cpu,6-> all_lpm,7-> all_transmit,8-> all_listen,9-> all_idle_transmit,10-> all_idle_listen,
#11->cpu,12-> lpm,13-> transmit,14-> listen, 15 ->idle_transmit, 16 -> idle_listen, [RADIO STATISTICS...]


from collections import defaultdict
cpuOverTime =  defaultdict(list)

with open('loglistener.txt', 'rb') as f:
    reader = csv.reader(f,delimiter=' ')
    for row in reader:
        if row[2] is 'P':
            cpuOverTime[row[3]].append(row[11])

for i in cpuOverTime:
    plt.plot(cpuOverTime[i])
plt.show()
########## 

1 个答案:

答案 0 :(得分:0)

在Python中,与大多数编程语言一样,偏移从0开始,而不是1。

从您的示例数据中我们可以看到P是行中第二个以空格分隔的项目,因此其索引为1:

Offset    0   | 1  | 2    | 3 | 4   | 5     | 6
Row       261 | P  | 0.18 | 0 | 834 | 64627 | 0 

要解决此问题,只需将索引更改为1:

with open('loglistener.txt', 'rb') as f:
    reader = csv.reader(f,delimiter=' ')
    for row in reader:
        if row[1] is 'P':
            cpuOverTime[row[3]].append(row[11])

我没有选中,但您可能会遇到与row[3]row[11]相同的问题