问题描述
对于一项任务(即没有大熊猫或其他任何使其更容易实现的任务),我必须在python3 / numpy / Matplotlib中绘制一个多边形,但是数据文件给我带来了第一道麻烦,我无法确定找出导致问题的原因。
.dat文件有两列,每行几行,如下所示:
(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“替换”不能使用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个仅包含所需数字的字符串列表时,我仍然得到了{ {1}}。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)