将文本文件中的特定行拆分为 python 中的 x、y 变量
python 186
原文标题 :Split specific line in text file to x, y variables in python
我在python中编写了一个读取文本文件(Test.text)的代码,文本文件包含如下数据
10 20
15 90
22 89
12 33
我可以通过使用此代码阅读特定行
particular_line = linecache.getline('Test.txt', 1)
print(particular_line)
我尝试使用代码将文本文件拆分为 x,y 值,但它得到了所有行而不是我需要的特定行
with open('Test.txt') as f:
x,y = [], []
for l in f:
row = l.split()
x.append(row[0])
y.append(row[1])
那么如何获取特定行并将其拆分为两个值 x 和 y
回复
我来回复-
Daweo 评论
你可能会做
particular_line = linecache.getline('Test.txt', 1) print(particular_line) x, y = particular_line.split() print(x) # 10 print(y) # 20
.split()
确实给出了包含 2 个元素的列表,我使用所谓的解包将第一个元素放入变量x
,将第二个元素放入y
。2年前 -
CarlosSR 评论
您缺少代码中的 readlines
with open('Test.txt') as f: x,y = [], [] for l in f.readlines(): row = l.split() x.append(row[0]) y.append(row[1])
2年前 -
Salvatore Daniele Bianco 评论
import pandas as pd xy = pd.read_csv("Test.txt", sep=" ", header=None).rename(columns={0:"x", 1:"y"})
现在您可以使用
xy.x.values
和xy.y.values
访问所有x
和y
值。请注意,我选择sep=" "
作为分隔符,因为我假设您的 x 和 y 在文件中由一个空格分隔。2年前 -
Freddy Mcloughlan 评论
这是一个相当精简的例子:
with open("input.txt", "r") as f: data = f.read() # Puts data into array line by line, then word by word words = [y.split() for y in data.split("\n")] # Gets first word (x) x = [x[0] for x in words] # Gets second word (y) y = [x[1] for x in words]
其中
[y.split() for y in data.split("\n")]
通过在\n
处拆分得到每一行,并通过它们之间的空间拆分 x 和 y 值 (.split()
)2年前 -
wavesun 评论
要获取特定行,您可以使用此代码
with open('Test.txt') as f: particular_line = f.readlines()[1] print(particular_line)
注意里面的索引
[]
,它从0
开始,和大多数其他语言一样。例如,如果要获取第一行,则将其更改为0
。通过将其解析为两个变量,您可以使用x, y = particular_line.split() print(x) print(y)
所以,把它们放在一起,
with open('Test.txt') as f: particular_line = f.readlines()[1] print(particular_line) x, y = particular_line.split() print(x) print(y)
您可能还需要函数格式,
def get_particular_line_to_x_y(filename, line_number): with open(filename) as f: particular_line = f.readlines()[line_number] return particular_line.split() if __name__ == '__main__': x, y = get_particular_line_to_x_y('Test.txt', 0) print(x) print(y)
2年前