'Dictionary has newline after a given number of characters
I use the pyshp library to retrieve the coordinates of a shape.
sf = shapefile.Reader(r"{}".format(boundary_file))
shapes = sf.shapes()
fields = sf.fields
records = sf.records()
for record in records:
if record['NAME'] in cities_list:
city = record['NAME']
s = sf.shape(record_id)
geom = s.__geo_interface__
geom_list = []
for dict in geom:
if dict == "coordinates":
coord_dict = geom[dict]
coords = coord_dict[0]
for pairs in coords:
geom_list.append(pairs)
Then I need to create a string based on the coordinates from the 'geom' dict. I use the function:
def listToString(s):
# initialize an empty string
str1 = ""
# traverse in the string
for ele in s:
str1 += "'{}',".format(ele)
# return string
return str1
I further process the string to remove any other character except for coordinates.
My problem is there is a newline present that I cannot remove.
When printing print(listToString(geom_list )) I notice that there is a newline after a particular number of characters
This is how it looks in notepad++.
I would like to remove the newline and print the list of coordinates in one string.
Solution 1:[1]
Instead of using the geo_interface, try accessing the geometry directly.
So instead of:
geom = s.__geo_interface__
Try:
geom = s.points
That will give you a list of python tuples which should be easier to manipulate. For example:
print(geom)
[(325596.92722995684, 1203960.6356796448), (325586.0020689714, 1203249.2743698577), (325583.88228647516, 1203111.9924421005), (325557.3214867797, 1203079.1636561346), (325492.1746068211, 1203066.062398915), (325493.67478956026, 1203251.0499563925), (325497.30834786664, 1203686.7895428804), (325500.8040477646, 1203877.5114580444)]
Then extend your geometry list:
geom_list.extend(geom)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GeospatialPython.com |
