【发布时间】:2021-02-13 04:08:41
【问题描述】:
对于一项任务(即没有 pandas 或任何使其更容易的东西),我必须在 python3/numpy/Matplotlib 中绘制一个多边形,但数据文件在第一关给我带来了麻烦,我想不出找出导致问题的原因。
.dat 文件有 2 列多行,每行如下所示:
(34235.453645, 68597.5469)
到目前为止,我已经想出了如何用.replace 删除每一行中的括号和逗号,这样就可以了:
34235.453645 68597.5469
用这个:
lang-js
#Assign columns
data_easting=[]
data_northing=[]
#Open the .dat file (in Python)
Poly = open('poly.dat','r')
#Loop over each line of poly.dat.
for replace in Poly.readlines():
#Replace the extraneous information ("(",",",")") with nothing, rather than multiple commands to strip and remove them. Stack Overflow Source for idea: https://stackoverflow.com/questions/390054/python-strip-multiple-characters.
replace = replace.replace('(','').replace(',','').replace(')','')
#Loop over the replaced data to split into lines 1(easting) and 2(northing) and append.
但是,当我想在最后的注释之后将返回的“替换”字符串拆分为 x 和 y(data_northing 和 _easting 列表)时,其中包含另一个 for 循环:
for line in replace.readlines():
x,y=line.split()
data_easting.append(x)
data_northing.append(y)
我收到一条错误消息,提示 str "replace" 不能使用 readlines 函数。
如果我删除缩进(两个 for 循环在同一级别),则会出现相同的错误。
如果我将前一个 for 循环中的“replace”替换为“Poly”,“list”只是 x,y 数据的第一行(print (x[n]) 只返回数字的第 n 个字符字符串)
如果我像这样将循环和命令组合在一起;
for replace, line in Poly.readlines():
x,y =line.split
data_easting.append(x)
data_northing.append(y)
并尝试命令我得到一个错误“行未定义”,或者我得到一个值错误: “ValueError:没有足够的值来解包(预期 2,得到 1)”
现在可能很明显,我对 Python 还是很陌生,不知道如何克服这个问题,继续绘制数据(我对此基本没问题)。我如何让第二个函数从第一个函数开始,我是否让第一个函数产生实际输出然后运行第二个命令(即“Make Poly2.dat”然后拆分该数据文件)?
当我四处寻找问题时,很多解决方案都提出了迭代器。可以在这里应用吗?
编辑:我最终放弃了这个并使用 .strip('()\n' 和 .split(', ') 来获取数据,但是现在虽然我有 2 个字符串列表,其中只有我需要的数字,但我仍然得到一个 Value Error; not enough values to unpack (expected 2, got 1)。
【问题讨论】:
标签: python python-3.x for-loop readlines