使用Numpy查找文件的特定行

2024-04-23 20:50:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用matplotlib制作一个包含文本和数字的文件信息的重量图表。数字是两行,其中有重量和日期。文件如下所示:

1. anonymous 
2. anonymous
3. 
4. 34, 76
5. 12202018, 12222018

我想使用numpy来检索权重(第3行)和日期(第4行),但是我找不到一种方法来检索matplotlib中要打印的一行。你知道吗

我试过用csv来做,但是没有用,因为当你制作一个列表来检索一行时,你不能在列表中绘制那一行。我的代码是:

import matplotlib.pyplot as plt
import csv

x = []
y = []

with 
open('example.txt') as csvfile:
    readCSV = list(csv.reader(csvfile, delimiter = ','))
    row3 = readCSV[3]

    for row in row3:
        x.append(int(row[0]))
        y.append(int(row[1]))

plt.plot(x, y)

plt.xlabel('x')
plt.ylabel('y')
plt.title("Weight Chart")
plt.legend()
plt.show()

产生的错误:

row3 = int(readCSV[3])
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

只是想澄清一下:

我想使用numpy检索文件的一行(delimeter为','),作为matplotlib的x和y轴。你知道吗

非常感谢!你知道吗


Tags: 文件csvimportnumpy列表matplotlibasplt
1条回答
网友
1楼 · 发布于 2024-04-23 20:50:14

这将把文件中的值放入数组:

def process(line):
    line = line.rstrip()
    line = line.split('.')[1]
    line = line.split(',')
    return line

x = list()
y = list()
counter = 0
with open('example.txt') as data_file:
    for line in data_file:
        if (counter == 3) or (counter == 4):
            result = process(line)
            x.append(int(result[0]))
            y.append(int(result[1]))
        counter += 1

print x
print y

相关问题 更多 >