gpt4 book ai didi

python - 如何在拆分字符串和数字之前避免包含字符串和数字的行?

转载 作者:行者123 更新时间:2023-12-01 08:21:44 24 4
gpt4 key购买 nike

我使用python 3,我读取的文件以几行开头,其中包含文本和数字,并且从某一行开始,它只是数字列,最初它们在分割后也被读取为str,我稍后将其转换他们漂浮。

数据看起来像这样。我还添加了数字样本的链接

https://gist.github.com/Farzadtb/b0457223a26704093524e55d9b46b1a8

enter image description here

所以问题是,对于阅读,我有两个条件(实际上我希望增加这些条件),使用 try: except 。但这仅适用于分割分割方法。但在开始分割之前,我需要删除包含文本的第一行。我知道我应该使用

除了值错误

但这并没有真正起作用!

f = io.open(file, mode="r", encoding="utf-8")
#f=open(file,"r")
lines=f.readlines()

x=[]
y=[]
z=[]

for i in lines:

try:
a=[i.strip('\n')]
a1=[float(n) for n in a[0].split(',')]
atot.append(a1)
x.append(a1[3])
y.append(a1[2])
z.append(a1[1])

except :
a=[i.split('\n')]
a1=[float(n) for n in a[0].split()]
x.append(a1[3])
y.append(a1[2])
z.append(a1[1])

问题是,由于第一行也可以以数字开头,因此第一个参数可能会被拆分并添加到“x”和“y”,但我收到 z 错误

x=[float(i) for i in x]
y=[float(i) for i in y]
z=[float(i) for i in z]

我想到的一个想法是检查该行是否可以无错误地转换为 float ,然后继续拆分,但我不知道该怎么做

最佳答案

你应该试试这个。此代码使用正则表达式以干净的方式查找数据。

import pprint
import re

if __name__ == '__main__':
# pattern to ignore line containing alpha or :
ignore_pattern = re.compile(r'[^a-zA-Z:]*[a-zA-Z:]')
# number pattern
number_pattern = re.compile(r'[-.\d]+')

matrix = []

# open the file as readonly
with open('data.txt', 'r') as file_:

# iterator over lines
for line in file_:
# remove \n and spaces at start and end
line = line.strip()
if not ignore_pattern.match(line):

found = number_pattern.findall(line)
if found:
floats = [float(x) for x in found]
matrix.append(floats)

# print matrix in pretty format
pp = pprint.PrettyPrinter()
pp.pprint(matrix)

# access value by [row][column] starting at 0
print(matrix[0][2])

对您的示例数据进行了测试。这是 python 脚本的标准输出:

[[-3.1923, 0.6784, -4.6481, -0.0048, 0.3399, -0.2829, 0.0, 24.0477],
[-3.1827, 0.7048, -4.6257, 0.0017, 0.3435, -0.2855, 0.0, 24.0477],
[-3.1713, 0.7237, -4.5907, 0.0094, 0.3395, -0.2834, 0.0, 24.0477]]
-4.6481

关于python - 如何在拆分字符串和数字之前避免包含字符串和数字的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54600340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com