读取绘图的文本文件值 - Python

时间:2021-04-12 15:44:25

I have a text file with values inside of it like so:

我有一个文本文件,其中包含值,如下所示:

1913 - 5,588,048
1914 - 4,202,179
1915 - 1,172,258
1916 - 2,481,675
1917 - 5,521,373
1918 - 6,052,289
1919 - 7,835,400 

1920 - 1929
1920 - 10,649,851
1921 - 2,582,495
1922 - 4,763,186

I want a 2D plot of these two columns of numbers. 19xx and x-axis, and the other column on the y-axis. I'm having trouble using split() to get rid of the ' - ' and also removing '' that appear for some reason.

我想要这两列数字的二维图。 19xx和x轴,另一列在y轴上。我在使用split()来摆脱' - '以及删除由于某种原因出现的''时遇到了麻烦。

My code so far:

我的代码到目前为止:

import numpy as np
import matplotlib.pyplot as plt

with open("Nickels.txt") as f:
    data = f.read()

data = data.split('\n')


data2 = [row.split(' - ',1) for row in data] # to get rid of ' - '
data2[:] = [item for item in x if item != ''] # to get rid of ''


x = []
y = []
for i in range(len(x)): #making lists
    x.append(0)
    y.append(0)
for j in enumerate(data2):
    x[i] = data2[:1]

print(x1)

#will proceed after part above works.
#fig = plt.figure()
#ax1.plot(x1,y1, c='r', label='Data')
#plt.show()

1 个解决方案

#1


1  

This code should solve your problem:

此代码应该可以解决您的问题:

import numpy as np import matplotlib.pyplot as plt

import numpy as np import matplotlib.pyplot as plt

x = []
y = []
with open('Nickels.txt') as file:
    for line in file:
        d1 = line.strip().split('-')   # Splits X and Y constituents
        if len(d1) !=2: continue       # Skips the empty lines

        d2 = d1[1].strip().split(',')  # Splits Y columns
        if len(d2) !=3: continue       # Skips range lines

        x.append(int(d1[0].strip()))   # Builds X
        y.append(int(''.join(d2)))     # Builds Y

Contents of x:

x的内容:

[1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922]

Contents of y:

y的内容:

[5588048,
 4202179,
 1172258,
 2481675,
 5521373,
 6052289,
 7835400,
 10649851,
 2582495,
 4763186]

#1


1  

This code should solve your problem:

此代码应该可以解决您的问题:

import numpy as np import matplotlib.pyplot as plt

import numpy as np import matplotlib.pyplot as plt

x = []
y = []
with open('Nickels.txt') as file:
    for line in file:
        d1 = line.strip().split('-')   # Splits X and Y constituents
        if len(d1) !=2: continue       # Skips the empty lines

        d2 = d1[1].strip().split(',')  # Splits Y columns
        if len(d2) !=3: continue       # Skips range lines

        x.append(int(d1[0].strip()))   # Builds X
        y.append(int(''.join(d2)))     # Builds Y

Contents of x:

x的内容:

[1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922]

Contents of y:

y的内容:

[5588048,
 4202179,
 1172258,
 2481675,
 5521373,
 6052289,
 7835400,
 10649851,
 2582495,
 4763186]