Я пытаюсь построить данные из файла, используя 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()
Большое спасибо за любую помощь!Я ценю это!