gpt4 book ai didi

python - Matplotlib 包含文件中的数据

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:30 24 4
gpt4 key购买 nike

我正在尝试使用 matplotlib 从文件中绘制数据。问题是该文件的每一行中可以有一个变量或两个变量。文件中还有文本。示例文件如下:

words
words
34, 34
132019, 232019

下面是我迄今为止创建的代码。代码的结果是什么都没有。没有图表或错误。我想知道是否有人知道完成这项任务的正确方法。

import matplotlib.pyplot as plt
import re

regex = r'[\d]{1,3}, [\d]{1,3}'
result = []

with open('example.txt', 'r') as my_file:
# Read file into a list
lines = [i for i in my_file]
# Check length of list at least four items
if len(lines) <= 4:
lines1 = my_file.readlines() # List containing all the lines as elements of the list

date_line = lines1[4]

len(date_line)

if len(date_line) <= 10:

上面的部分是查看文件的行中是否只有一个变量,还是两个。

            # Read in values and strip white space

x = []
y = []

weight = lines[3].strip()
date = lines[4].strip()

weight1 = int(weight)
date1 = int(date)

x.append(date1)
y.append(weight1)

plt.plot(x, y)
plt.xlabel("Dates")
plt.ylabel("Weights")
plt.title("Weight Chart")
plt.show()

else:

lines = my_file.readlines()
for line in lines:
match = re.findall(regex, line)
if match != []:
splitted = match[0].split(',')
mapped = list(map(float, splitted))
result.append(mapped)

plt.plot(result)
plt.xlabel("Dates")
plt.ylabel("Weights")
plt.title("Weight Chart")
plt.show()

非常感谢您的帮助!我很感激!

最佳答案

您使用以下内容读取文件

lines = [i for i in my_file]

但是您尝试使用 readlines 再次读取该文件 - 没有更多内容可读取!只需再次使用lines即可。

关于python - Matplotlib 包含文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54032500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com