[英]Matplotlib with data from a file
我正在尝试使用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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.