我正在从网络上读取文本文件。该文件以一些包含数据点数量的标题行开始,后面是实际顶点(每个顶点 3 个坐标)。该文件如下所示:
# comment
HEADER TEXT
POINTS 6 float
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
POLYGONS
以单词 POINTS
开头的行包含顶点数(在本例中,每行有 3 个顶点,但这可能会改变)
这就是我现在阅读的方式:
ur=urlopen("http://.../file.dat")
j=0
contents = []
while 1:
line = ur.readline()
if not line:
break
else:
line=line.lower()
if 'points' in line :
myline=line.strip()
word=myline.split()
node_number=int(word[1])
node_type=word[2]
while 'polygons' not in line :
line = ur.readline()
line=line.lower()
myline=line.split()
i=0
while(i<len(myline)):
contents[j]=float(myline[i])
i=i+1
j=j+1
如何读取指定数量的 float ,而不是逐行读取字符串并转换为 float ?
我想读取文件中指定数量的元素,而不是 ur.readline()
欢迎任何建议..
最佳答案
从你的解释中我不完全确定你的目标是什么。
郑重声明,这里的代码与您的代码执行的操作基本相同,这些代码似乎使用了一些我会在您选择的技术上采用的技术。如果您使用 while 循环和索引,这通常表明您做错了什么,并且您的代码确实无法工作,因为 contents[j] = ...
将是一个 IndexError
.
lines = (line.strip().lower() for line in your_web_page)
points_line = next(line for line in lines if 'points' in line)
_, node_number, node_type = points_line.split()
node_number = int(node_number)
def get_contents(lines):
for line in lines:
if 'polygons' in line:
break
for number in line.split():
yield float(number)
contents = list(get_contents(lines))
如果您更明确地了解您想要做的新事物,也许有人可以为您的最终目标提供更好的答案。
关于python - 如何从python文件中读取特定数量的 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2679290/