[英]Python: Reading and obtaining certain parts of a text file
I have a text file that has coordinates in a format of [x1, y1, x2, y2]
.我有一个文本文件,其坐标格式为
[x1, y1, x2, y2]
。 How would I be able to obtain just the y1
and y2
coordinates?我怎样才能获得
y1
和y2
坐标?
Example:例子:
[23, 45, 90, 79]
Obtain 45
and 79
获得
45
和79
x = [23, 45, 90, 79]
x[1]
will be 45
and x[3]
will be 79. So you can print them as print(x[1],x[3])
.The output will be 45 79
x[1]
将为45
, x[3]
将为 79。因此您可以将它们打印为print(x[1],x[3])
。output 将为45 79
x = [[23, 45, 90, 79],[191, 64, 243, 93],[437, 76, 514, 127]]
for i in range(len(x)):
print(x[i][1],x[i][3])
will print:将打印:
45 79
64 93
76 127
If the coordinates always remain at the same position you could use:如果坐标始终保持不变 position 您可以使用:
array = [23,45,90,79]
y1_y2 = [array[1], array[3]]
This will do:这将做:
import re
with open('text.txt', 'r') as f:
for line in f.readlines():
x, y = re.findall(r'\d+.*?(\d+).*?\d+.*?(\d+)', line)[0]
print(x,y)
If your data is a string like s
in the given code, Use the strip functions to remove [
, ]
and use the split function, otherwise convert the list, s = [23, 45, 90, 79]
into an string by s = str(s)
:如果您的数据是给定代码中类似
s
的字符串,请使用 strip 函数删除[
, ]
并使用拆分 function ,否则将列表s = [23, 45, 90, 79]
转换为s = str(s)
字符串s = str(s)
:
s = '[23, 45, 90, 79]'
s = s.strip('[').strip(']').split(',')
#Now getting y1 and y2 :
y1 = int(s[1]) # You can use the float() function if needed
y2 = int(s[3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.