使用python添加行号和计数量

时间:2016-12-23 08:33:01

标签: python

我有一个来自地理信息系统的文件,我需要在arcgis中使用该文件的一部分并在那里制作一个功能。

这是该档案的一部分:

<PropertyValuePair property="LineControlCategory" value="BDYOR" />
    <PropertyValuePair property="Location" value="|0|LINESTRING (-64.9734423 46.8886667 0, -64.975073 46.9527568 0, -65.015054 46.9900623 0, -65.0746205 47.0712622 0, -65.0990984 47.0740409 0, -65.1456079 47.0551434 0, -65.1505056 47.0451361 0, -65.2100694 47.0445795 0, -65.2010947 47.0712622 0, -65.204359 47.0834863 0, -65.2206776 47.0834863 0, -65.2476043 47.0740409 0, -65.2720821 47.0829311 0, -65.2916649 47.066815 0, -65.3357282 47.0801523 0, -65.3732604 47.0773749 0, -65.4219264 47.0582964 0)" />
    <PropertyValuePair property="ObjectLabelA" value="13" />
    <PropertyValuePair property="LineControlCategory" value="BDYOR" />
    <PropertyValuePair property="Location" value="|0|LINESTRING (-65.4401144 46.9992797 0, -65.4268321 47.0112236 0, -65.4351497 47.030746 0, -65.4126433 47.0448317 0, -65.4213041 47.0585458 0)" />
    <PropertyValuePair property="ObjectLabelA" value="para mil force" />

我现在的python脚本给了我:

X,Y,Feature,FeatureOrder
-64.9734423,46.8886667,
-64.975073,46.9527568,
-65.015054,46.9900623,
-65.0746205,47.0712622,
-65.0990984,47.0740409,

我需要做什么才能在arcgis中使用我需要行号和订单号。所以像这样:

X,Y,Feature,FeatureOrder
-64.9734423,46.8886667,1,1
-64.975073,46.9527568,1,2
-65.015054,46.9900623,1,3
Etc
-65.4401144,46.9992797,2,1
-65.4268321,47.0112236,2,2
-65.4351497 47.030746,2,3
-65.4126433,47.0448317,2,4

第一个数字1来自第一行,其中包含“位置”。第二个数字是该行中数字范围的顺序。 这是我现在的脚本:

f = open('OVERLAY.ovl','r')
file = open("newfile.txt", "w")
file.write("X,Y,Feature,FeatureOrder\n")

for line in f.readlines():
    if "Location" in line:
        file.write(line.split("(")[1].split(")")[0].replace(", ", "\n").replace(" 0", ",\n").replace(" ", ","))

f.close()
file.close()

我希望同一个人可以帮助我 问候 彼得

1 个答案:

答案 0 :(得分:0)

鉴于代码,可能很难实现。这条线

file.write(line.split("(")[1].split(")")[0].replace(", ", "\n").replace(" 0", ",\n").replace(" ", ","))

是不可读的单行。至少应该重构

content = line.split("(")[1].split(")")[0]
rows = [y.replace(" ", ",") for x in content.split(', ')
                            for y in x.split(' 0')]
file.writelines(rows)

仍然很脏,但足够干净以改变代码行为:

for i, line in enumerate(f.readlines(), 1):
    if "Location" in line:
        content = line.split("(")[1].split(" 0)")[0]
        rows = [y.replace(" ", ",") for x in content.split(', ')
                                    for y in x.split(' 0')
                                    if  y != '']
        file.writelines(['{},{},{}\n'.format(row,i,j)
                         for j, row in enumerate(rows, 1)])