如何从文本文件中提取数据并将其添加到列表中?

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

这里是Python菜鸟。我有这个文本文件,其中的数据以特定方式排列,如下所示。

x = 2,4,5,8,9,10,12,45
y = 4,2,7,2,8,9,12,15

我想从中提取x值和y值并将它们放入各自的数组中以绘制图形。我查看了一些来源,但找不到特定的解决方案,因为它们都使用“readlines()”方法,该方法以包含 2 个字符串的列表形式返回。我可以将字符串转换为整数,但我面临的问题是如何只提取数字而不提取其余部分? 我确实写了一些代码;


#lists for storing values of x and y
x_values = []
y_values = []

#opening the file and reading the lines
file = open('data.txt', 'r')
lines = file.readlines()

#splitting the first element of the list into parts
x = lines[0].split()

#This is a temporary variable to remove the "," from the string
temp_x = x[2].replace(",","")

#adding the values to the list and converting them to integer. 
for i in temp_x:
     x_value.append(int(i))

这样就完成了工作,但是我认为这个方法太粗糙了。有更好的方法吗?

python data-extraction
3个回答
1
投票

您可以使用

read().splitlines()
removeprefix()
:

with open('data.txt') as file:
    lines = file.read().splitlines()
    x_values = [int(x) for x in lines[0].removeprefix('x = ').split(',')]
    y_values = [int(y) for y in lines[1].removeprefix('y = ').split(',')]

print(x_values)
print(y_values)

# output:
# [2, 4, 5, 8, 9, 10, 12, 45]
# [4, 2, 7, 2, 8, 9, 12, 15]

0
投票

由于您是Python新手,这里有一个提示! :永远不要在未关闭文件的情况下打开文件,通常的做法是使用

with
来防止这种情况,至于您的解决方案,您可以这样做:

with open('data.txt', 'r') as file:
    # extract the lines
    lines = file.readlines()

    # extract the x and y values
    x_values = [
        int(el) for el in lines[0].replace('x = ', '').split(',') if el.isnumeric()
        ]
    y_values = [
        int(el) for el in lines[1].replace('y = ', '').split(',') if el.isnumeric()
        ]

# the final output
print(x_values, y_values)

输出:

[2, 4, 5, 8, 9, 10, 12] [4, 2, 7, 2, 8, 9, 12, 15]

0
投票

使用字典来存储数据。

# read data from file
with open('data.txt', 'r') as fd:
    lines = fd.readlines()

# store in a (x,y)-dictionary
out = {}
for label, coord in zip(('x', 'y'), lines):
    # casting strings to integers
    out[label] = list(map(int, coord.split(',')[1:])) 

# display data
#
print(out)
#{'x': [4, 5, 8, 9, 10, 12, 45], 'y': [2, 7, 2, 8, 9, 12, 15]}
print(out['y'])
#[2, 7, 2, 8, 9, 12, 15]

如果所需的输出为列表,只需将主要部分替换为

out = []
for coord in lines:
    # casting strings to integers
    out.append(list(map(int, coord.split(',')[1:])))
X, Y = out
© www.soinside.com 2019 - 2024. All rights reserved.