在Python中从txt文件读取数组来绘制图表

问题描述 投票:0回答:1

我是 python 新手,想使用 txt 文件上的数组中存储的数据绘制图表...

txt 文件中的内容只是数组...没有其他..示例:

数组.txt

[0, 1, 10, 5, 40, 1, 70] [12, 54, 6, 11, 1, 0, 50]

就是这样...两个或多个带括号的数组,没有其他东西..

我想读取每个数组并将它们加载到变量中以使用 matplotlib 在 python 中绘制图形

import matplotlib.pyplot as plt

# import arrays from file as variables
a = [array1]
b = [array2]

plt.plot(a)
plt.plot(b)
plt.show()

我唯一需要的是如何从txt中读取数组并将它们加载到变量中以便稍后绘制它们......

我搜索了很多,但也发现了太多的方法可以用 python 做很多事情,这很好,但也让人不知所措

python arrays matplotlib text-files txt
1个回答
0
投票

文本文件的格式确实很不幸 - 最好解决问题的根源并以标准格式输出值(如 Json、XML 等)

您可以尝试手动解析文件(例如使用

re
/
json
模块):

import json
import re

import matplotlib.pyplot as plt

with open("your_file.txt", "r") as f_in:
    data = re.sub(r"]\s*\[", r"], [", f_in.read(), flags=re.S)

data = json.loads(f"[{data}]")

for i, arr in enumerate(data, 1):
    plt.plot(arr, label=f"Array {i}")

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title(f"Graph of {len(data)} Arrays")

plt.legend()
plt.show()

创建此图表:

© www.soinside.com 2019 - 2024. All rights reserved.