Reading kml file using python - python

I have been battling for days to read coordinates LineString using fastkml library in python.
I have imported geometry module in my main program. I am reading like this.
My kml file is stored in string called doc
X = Geometry
Z=x._get,_coordinates(doc)
I got an error that says
the module object has no attributes find

from fastkml import kml
import re
from fastkml.geometry import Geometry
from lxml import etree
from xml.etree import ElementTree
from io import StringIO, BytesIO
def print_child_features(element):
if not getattr(element, 'features', None):
return
for feature in element.features():
y = feature.to_string()
return y
def print_child2_features(element):
""" Prints the name of every child node of the given element, recursively """
if not getattr(element, 'features', None):
return
for feature in element.features():
print feature.name
print_child2_features(feature)
def get_distance(coordinates_str):
"""gets distance of one path from coordinates string in form of:
14.81363432237944,53.57016581501523,0 14.81411766813742,53.56923005549378,0 14.81880340335202,53.56879451890311 ...
look at:
http://code.google.com/intl/pl-PL/apis/kml/documentation/kmlreference.html#coordinates
"""
sum_distance = 0.0
arr = []
coordinates = []
if ' ' in coordinates_str:
arr = coordinates_str.split(' ')
if len(arr) > 1:
for s in arr:
if ',' in s:
pt = s.split(',')
pos_latt = (float(pt[0].strip()), 0, 0)
pos_long = (float(pt[1].strip()), 0, 0)
position = (pos_latt, pos_long)
coordinates.append(position)
if coordinates:
for i in range(len(coordinates) - 1):
start = coordinates[i]
stop = coordinates[i + 1]
sum_distance += distance.points2distance(start, stop)
return sum_distance
if name == 'main':
#fname = input("Enter KML file name ")
fname = "DBN.kml"
k = kml.KML()
with open(fname) as kmlFile:
k.from_string(kmlFile.read())
x = Geometry()
doc = print_child_features(k)
z= x._get_coordinates(doc)
print z
length=0
if length <= 10:
print("Transciver is LR")
elif length > 10 and length <= 40:
print("Transciver is ER")
else:
print("Transciver is ER")

I did not get the code you have written. But I have written code to read coordinates from Linestrings and other Geometries using fastkml library, so I can help.
# import necessary modules
from fastkml import kml, geometry
k = kml.KML() # create fastkml object
k.from_string(doc.encode('utf-8')) # read doc string
document = list(k.features())
self.parse_placemarks(document)
# parse features throughout the KML File
def parse_placemarks(self, document):
for feature in document:
if isinstance(feature, kml.Placemark): # when there is no folder
placemark = feature
self.parse_geometries(placemark)
for feature in document:
if isinstance(feature, kml.Folder):
self.parse_placemarks(list(feature.features()))
if isinstance(feature, kml.Document):
self.parse_placemarks(list(feature.features()))
# parse geometry
def parse_geometries(self, placemark):
if hasattr(placemark, "geometry"):
if isinstance(placemark.geometry, geometry.LineString):
self.linestring(placemark)
# parse linestring
def linestring(self, line):
x, y = self.compute_coordinates(line.geometry)
# find coordinates
def compute_coordinates(self, geometry):
lons = []
lats = []
for coordinates in geometry.coords:
lons.append(coordinates[0])
lats.append(coordinates[1])
return (lons, lats)
You can find how to extract coordinates of other geometries and more about fastkml here : https://medium.com/#wwaryan/the-definite-only-guide-to-fastkml-58b8e19b8454

Related

How to import elements from a vector file into a temporary layer with pyqgis

I want to get the temporary layer after converting the projection, but the code is invalid
project = QgsProject.instance()
project.read(path)
vector_layer = QgsVectorLayer(r"F:\test.shp", "test")
v2 = QgsVectorLayer("MultiPolygon?crs=epsg:4326&index=yes", "temporary_MultiPolygon", "memory")
transform = QgsCoordinateTransform(vector_layer.crs(),
QgsCoordinateReferenceSystem("EPSG:4326"), project)
for feature in vector_layer.getFeatures():
g = feature.geometry()
a = g.transform(transform)
feature.setGeometry(g)
if a == QgsGeometry.Success:
f = QgsFeature()
f.setGeometry(g)
print(f.geometry().boundingBox())
re = v2.addFeature(feature=f)
r = v2.addFeature(feature)
print(re)
else:
print("fail")
v2.updateExtents()
re = v2.addFeature(feature=f)
This code returns False
feature is a MultiPolygon

Trying to parse Word Documents and getting PdfReadError: EOF marker not found

I am testing some Python code to loop through resumes, open each, parse each, and create a comprehensive report based on the contents of each resume. Here is the code that I am running.
#importing all required libraries
import PyPDF2
import os
from os import listdir
from os.path import isfile, join
from io import StringIO
import pandas as pd
from collections import Counter
import en_core_web_sm
nlp = en_core_web_sm.load()
from spacy.matcher import PhraseMatcher
#Function to read resumes from the folder one by one
mypath='C:\\path_to_resumes\\' #enter your path here where you saved the resumes
onlyfiles = [os.path.join(mypath, f) for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]
def pdfextract(file):
fileReader = PyPDF2.PdfFileReader(open(file,'rb'))
countpage = fileReader.getNumPages()
count = 0
text = []
while count < countpage:
pageObj = fileReader.getPage(count)
count +=1
t = pageObj.extractText()
print (t)
text.append(t)
return text
#function to read resume ends
#function that does phrase matching and builds a candidate profile
def create_profile(file):
text = pdfextract(file)
text = str(text)
text = text.replace("\\n", "")
text = text.lower()
#below is the csv where we have all the keywords, you can customize your own
keyword_dict = pd.read_csv('D:/NLP_Resume/resume/template_new.csv')
stats_words = [nlp(text) for text in keyword_dict['Statistics'].dropna(axis = 0)]
NLP_words = [nlp(text) for text in keyword_dict['NLP'].dropna(axis = 0)]
ML_words = [nlp(text) for text in keyword_dict['Machine Learning'].dropna(axis = 0)]
DL_words = [nlp(text) for text in keyword_dict['Deep Learning'].dropna(axis = 0)]
R_words = [nlp(text) for text in keyword_dict['R Language'].dropna(axis = 0)]
python_words = [nlp(text) for text in keyword_dict['Python Language'].dropna(axis = 0)]
Data_Engineering_words = [nlp(text) for text in keyword_dict['Data Engineering'].dropna(axis = 0)]
matcher = PhraseMatcher(nlp.vocab)
matcher.add('Stats', None, *stats_words)
matcher.add('NLP', None, *NLP_words)
matcher.add('ML', None, *ML_words)
matcher.add('DL', None, *DL_words)
matcher.add('R', None, *R_words)
matcher.add('Python', None, *python_words)
matcher.add('DE', None, *Data_Engineering_words)
doc = nlp(text)
d = []
matches = matcher(doc)
for match_id, start, end in matches:
rule_id = nlp.vocab.strings[match_id] # get the unicode ID, i.e. 'COLOR'
span = doc[start : end] # get the matched slice of the doc
d.append((rule_id, span.text))
keywords = "\n".join(f'{i[0]} {i[1]} ({j})' for i,j in Counter(d).items())
## convertimg string of keywords to dataframe
df = pd.read_csv(StringIO(keywords),names = ['Keywords_List'])
df1 = pd.DataFrame(df.Keywords_List.str.split(' ',1).tolist(),columns = ['Subject','Keyword'])
df2 = pd.DataFrame(df1.Keyword.str.split('(',1).tolist(),columns = ['Keyword', 'Count'])
df3 = pd.concat([df1['Subject'],df2['Keyword'], df2['Count']], axis =1)
df3['Count'] = df3['Count'].apply(lambda x: x.rstrip(")"))
base = os.path.basename(file)
filename = os.path.splitext(base)[0]
name = filename.split('_')
name2 = name[0]
name2 = name2.lower()
## converting str to dataframe
name3 = pd.read_csv(StringIO(name2),names = ['Candidate Name'])
dataf = pd.concat([name3['Candidate Name'], df3['Subject'], df3['Keyword'], df3['Count']], axis = 1)
dataf['Candidate Name'].fillna(dataf['Candidate Name'].iloc[0], inplace = True)
return(dataf)
#function ends
#code to execute/call the above functions
final_database=pd.DataFrame()
i = 0
while i < len(onlyfiles):
file = onlyfiles[i]
dat = create_profile(file)
final_database = final_database.append(dat)
i +=1
print(final_database)
#code to count words under each category and visulaize it through Matplotlib
final_database2 = final_database['Keyword'].groupby([final_database['Candidate Name'], final_database['Subject']]).count().unstack()
final_database2.reset_index(inplace = True)
final_database2.fillna(0,inplace=True)
new_data = final_database2.iloc[:,1:]
new_data.index = final_database2['Candidate Name']
#execute the below line if you want to see the candidate profile in a csv format
#sample2=new_data.to_csv('sample.csv')
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 10})
ax = new_data.plot.barh(title="Resume keywords by category", legend=False, figsize=(25,7), stacked=True)
labels = []
for j in new_data.columns:
for i in new_data.index:
label = str(j)+": " + str(new_data.loc[i][j])
labels.append(label)
patches = ax.patches
for label, rect in zip(labels, patches):
width = rect.get_width()
if width > 0:
x = rect.get_x()
y = rect.get_y()
height = rect.get_height()
ax.text(x + width/2., y + height/2., label, ha='center', va='center')
plt.show()
In the folder, I have '.doc' and '.docx' files. Everything seems to work fine, up until this point, directly below. When I get here, the code throws an error. Here is the troublesome code. The weird thing is, that it looks like some kind of PDF error, but I'm iterating only through '.doc' and '.docx' files.
final_database=pd.DataFrame()
i = 0
while i < len(onlyfiles):
file = onlyfiles[i]
dat = create_profile(file)
final_database = final_database.append(dat)
i +=1
print(final_database)
Here is the StackTrace:
Traceback (most recent call last):
File "<ipython-input-2-c63fca79d39f>", line 5, in <module>
dat = create_profile(file)
File "<ipython-input-1-cdc3bf75cd26>", line 34, in create_profile
text = pdfextract(file)
File "<ipython-input-1-cdc3bf75cd26>", line 17, in pdfextract
fileReader = PyPDF2.PdfFileReader(open(file,'rb'))
File "C:\Users\ryans\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1084, in __init__
self.read(stream)
File "C:\Users\ryans\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1696, in read
raise utils.PdfReadError("EOF marker not found")
PdfReadError: EOF marker not found
The code comes from here.
https://towardsdatascience.com/do-the-keywords-in-your-resume-aptly-represent-what-type-of-data-scientist-you-are-59134105ba0d
You are using package PyPDF2, which is used to read and manipulate pdf files. In the article from towardsdatascience that you mentioned all resumes that author was working on were in pdf format.
Maybe if your resumes are in doc/docx format you should explore python-docx library:
https://python-docx.readthedocs.io/en/latest/index.html

Why after calling a function from an imported python file within a file the PyQt app stops responding?

I have created a PyQt5 GUI in my main.py file which is in a main app folder. In the file for the interface, a button initiates a new class called Calculation (in the file entry.py) passing in the values of several inputs on the page and in this class the startCalculation() method is called. In this method, the different variables are passed to methods in imported python files, then the result of those calculation is returned and passed to the next calculation in another python file. These returns are in the form of arrays containing values (for the y axis which is then displayed using numpy and plotly).
When I run the app and click on the button in the main interface, the app starts loading (rainbow animation on Mac) and it says it is not responding. It is not a problem with the class itself as a normal print test works in the startCalculation() method, but the function from the imported file causes this to happen. Also, no errors are given in the terminal.
The following is code in the PyQt interface file (main.py)
from app import entry
def startButton(self):
massaTotale = float(self.lineEdit.text())
dragCoefficient = float(self.lineEdit_5.text())
liftCoefficient = float(self.lineEdit_6.text())
powerAvionics = float(self.lineEdit_3.text())
powerPayload = float(self.lineEdit_4.text())
airSpeed = float(self.lineEdit_8.text())
valoreUnico = float(self.valoreUnicoEdit.text())
engineEfficiency = float(self.lineEdit_9.text())
turbolenceCoeff = float(self.lineEdit_10.text())
dayOfYear = float(self.day_LineEdit.text())
latitude = float(self.latitude_LineEdit.text())
sunsetHourAngle = float(self.sunsetHourAngle_LineEdit.text())
declination = float(self.declination_LineEdit.text())
newCaluclation = entry.Calculation(massaTotale, dragCoefficient, liftCoefficient, powerAvionics, powerPayload, airSpeed, valoreUnico, engineEfficiency, turbolenceCoeff, dayOfYear, latitude, sunsetHourAngle, declination)
newCaluclation.startCalculation()
And this is the code in the class calling the function in the external file
from app.mainFunctions import pLevel
#constructor method
def __init__(self, massaTotale, dragCoefficient, liftCoefficient, powerAvionics, powerPayload, airSpeed, valoreUnico, efficiencyEngine, turbolenceCoeff, dayOfYear, latitude, sunsetHourAngle, declination):
# calculate plevel
self.totM = massaTotale
self.vair = airSpeed
self.cl = liftCoefficient
self.cd = dragCoefficient
self.efficiencyEngine = efficiencyEngine
self.valoreUnico = valoreUnico
self.powerAvionics = powerAvionics
self.powerPayload = powerPayload
self.turbolenceCoeff = turbolenceCoeff
self.day_of_year = dayOfYear
self.latitude = latitude
self.sunset_hour_angle = sunsetHourAngle
self.declination = declination
#starting the calculation
def startCalculation(self):
self.x_values, self.pLevel_values = pLevel.calculate_pLevel(self.valoreUnico, self.cd, self.cl, self.totM)
'''
self.pEngine_values = pEngine.calculate_pEngine(self.x_values, self.pLevel_values, self.efficiencyEngine, self.turbolenceCoeff)
self.pOut_values = pOut.calculate_pOut(self.x_values, self.pEngine_values, self.powerAvionics, self.powerPayload)
self.I_loctime = I_loctime.calculate_I_loctime(self.day_of_year, self.latitude, self.sunset_hour_angle, self.declination)
self.asm_values = area_Solar_Module.calculate_asm(self.x_values, self.pOut_values, self.I_loctime)
'''
The pLevel.py file has the following code in it and should return the array of values to pass to the second function in the entry Calculation class file.
import math
import numpy as np
import plotly as py
import plotly.graph_objs as go
import ipywidgets as widgets
import plotly.io as pio
import sys
sys.dont_write_bytecode = True
py.offline.init_notebook_mode(connected=True)
pio.renderers.default = "browser"
# calculating pLevel
x_values = []
y_values = []
layoutPLevel = go.Layout(
title="pLevel",
yaxis=dict(
title='pLevel'
),
xaxis=dict(
title='Surface Area Wing'
)
)
def calculate_pLevel(valoreUnico, cd, cl, totM):
x_values = []
count = 0
while (count < 5):
x_values.append(count)
count = count + 0.01
y_values = []
iteration = 0
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
else:
if (valoreUnico == 0.0):
# nessun dato per valoreUnico dato, utilizza i due valori separati
y_value = firstPart(cd, cl) * math.sqrt(secondPart(x_value, totM))
y_values.append(y_value)
else:
y_value = valoreUnico * \
math.sqrt(secondPart(x_value, totM))
y_values.append(y_value)
iteration = iteration + 1
else:
yNpArray = np.array(y_values)
xNpArray = np.array(x_values)
tracePLevel = go.Scatter(
x=xNpArray,
y=yNpArray,
mode='lines',
name='pLevel',
line=dict(
shape='spline'
)
)
figPLevel = go.Figure(data=[tracePLevel], layout=layoutPLevel)
figPLevel.show()
return x_values, y_values
def firstPart(cd, cl):
return (cd / cl**(3/2))
def secondPart(x_value, totM):
return (2*(totM * 9.81)**3) / (1.225 * x_value)
The structure of the files is as follows:
-app
-- __main__.py
-- entry.py
-- __init__.py
-- mainFunctions
--- pLevel.py
--- __init__.py
The loop for the x_values in the pLevel function was not adding one to the iteration so the loop went on forever. I just did not notice my error.
Instead of being
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
It should be
while (iteration < len(x_values)):
x_value = x_values[iteration]
if (x_value == 0):
y_value = 0
y_values.append(y_value)
iteration = iteration+1

Convert dxf to bmp write on python

Do you know good library (write on python) for converting dxf files to bmp?
I have a folder with "filename_number" dxf files.
I want read it and convert it to bmp. Also I want keep file's dimension size.
I got the answer from here:
import StringIO, base64, logging, operator
import dxfgrabber
import Image, ImageDraw, ImageFont #PIL
from homcoord import *
def rint(x):return int(round(x))
class BBox:
"""bounding box"""
def __init__(self,pt1=None,pt2=None):
self._corner1=None
self._corner2=None
if pt1: self+=pt1
if pt2: self+=pt2
def __iadd__(self,pt):
if isinstance(pt,BBox):
self+=pt._corner1
self+=pt._corner2
else:
if not self._corner1:
self._corner1=pt
else:
self._corner1=Pt(map(min,zip(self._corner1.xy,pt.xy)))
if not self._corner2:
self._corner2=pt
else:
self._corner2=Pt(map(max,zip(self._corner2.xy,pt.xy)))
return self
def __repr__(self):
return "BBox(%s,%s)"%(self._corner1,self._corner2)
def __call__(self):
""":return: list of flatten corners"""
l=list(self._corner1.xy)
l.extend(list(self._corner2.xy))
return l
def size(self):
""":return: Pt with xy sizes"""
return self._corner2-self._corner1
def center(self):
""":return: Pt center"""
res=self._corner2+self._corner1
return res/2
def trans(self,trans):
"""
:param trans: Xform
:return: BBox = self transformed by trans
"""
return BBox(trans(self._corner1),trans(self._corner2))
def cbox(c,r):
""" bounding box of a circle
:param c: Pt center
:param r: float radius
:return: BBox
"""
rr=Pt(r,r)
return BBox(c+rr,c-rr)
def Trans(scale=1, offset=[0,0], rotation=0):
res=Xform([[scale,0,offset[0]],[0,scale,offset[1]],[0,0,1]])
if rotation:
res=Xrotate(rotation*pi/180.)*res
return res
class DXF:
def __init__(self, file, layers=None, ignore=[]):
"""reads a .dxf file
:param file: string path to .dxf file to read
:param layers: list or dictionary of layers to handle. Empty = all layers
:param ignore: list of strings of entity types to ignore
"""
self.dxf=dxfgrabber.readfile(file)
self.layers=layers
self.ignore=ignore
def entities(self,ent=None):
"""iterator over dxf or block entities"""
if not ent:
ent=self.dxf.entities
for e in ent:
if self.layers and e.layer not in self.layers:
continue
elif e.dxftype in self.ignore:
continue
else:
yield e
def bbox(self):
""":return: :class:BBox dwg enclosing bounding box"""
box=BBox()
for e in self.entities():
if e.dxftype=='LINE':
box+=Pt(e.start[:2])
box+=Pt(e.end[:2])
elif e.dxftype == 'CIRCLE':
box+=cbox(Pt(e.center[:2]),e.radius)
elif e.dxftype == 'ARC':
c=Pt(e.center[:2])
a=e.endangle-e.startangle
if a>0:
start=e.startangle
else: #arc goes clockwise (step will be negative)
start=e.endangle
n=rint(abs(a)/10.) # number of points each 10° approximately
n=max(n,1)
step=a/n #angle between 2 points, might be negative
for i in range(n+1):
box+=c.radial(e.radius,radians(start+i*step))
elif e.dxftype=='POLYLINE':
for v in e.vertices:
box+=Pt(v.location[:2])
elif e.dxftype=='BLOCK':
pass #TODO ...
elif e.dxftype in ['TEXT','INSERT']:
box+=Pt(e.insert[:2])
else:
logging.warning('Unknown entity %s'%e)
return box
def _draw(self,draw,entities,trans,pen="black"):
for e in entities:
if e.dxftype=='LINE':
b=list(trans(Pt(e.start[:2])).xy)
b.extend(list(trans(Pt(e.end[:2])).xy))
draw.line(b,fill=pen)
elif e.dxftype=='CIRCLE':
b=cbox(Pt(e.center[:2]),e.radius)
b=b.trans(trans)
draw.ellipse(b(),outline=pen)
elif e.dxftype=='ARC':
c=Pt(e.center[:2])
b=cbox(c,e.radius)
b=b.trans(trans)
b=map(rint,b())
startangle=degrees(trans.angle(radians(e.startangle)))
endangle=degrees(trans.angle(radians(e.endangle)))
startangle,endangle=endangle,startangle #swap start/end because of Y symmetry
draw.arc(b,int(startangle),int(endangle),fill=pen)
elif e.dxftype=='POLYLINE':
b=[]
for v in e.vertices:
b.extend(list(trans(Pt(v.location[:2])).xy))
draw.line(b,fill=pen)
elif e.dxftype=='TEXT':
h=e.height*trans.mag()
pt=Pt(e.insert[:2])+Pt(0,e.height) #ACAD places texts by top left point...
font=None
try:
font = ImageFont.truetype("c:/windows/fonts/Courier New.ttf", rint(h))
except:
pass
if not font:
h=h*1.4 #magic factor ...
fh=[8,10,12,14,16,18,20,22,24,26,28,30,36,40,48,60]
i,h=min(enumerate(fh), key=lambda x: abs(x[1]-h)) #http://stackoverflow.com/questions/9706041/finding-index-of-an-item-closest-to-the-value-in-a-list-thats-not-entirely-sort
import os
path=os.path.realpath(__file__)
path=os.path.dirname(path)
font = ImageFont.load(path+'\\base_pil\\72\\Courier New_%s_72.pil'%h)
draw.text(trans(pt).xy,e.text,font=font,fill=pen)
elif e.dxftype=='INSERT':
t2=Trans(1,e.insert,e.rotation).compose(trans)
self._draw(draw,self.entities(self.dxf.blocks[e.name]._entities),t2,pen)
elif e.dxftype=='BLOCK':
pass # block definition is automatically stored in dxf.blocks dictionary
else:
logging.warning('Unknown entity %s'%e)
def img(self,size=[256,256],back="white",pen="black",border=5,antialias=1):
""":result: :class:`PIL:Image` rasterized image"""
box=self.bbox()
from Goulib.math2 import product
if not product(box.size().xy): # either x or y ==0
return None
s=map(operator.div,[float(x-border)*antialias if x else 1E9 for x in size ],box.size().xy)
trans=Trans(scale=min(s))
size=trans(box.size())+Pt(2*antialias*border,2*antialias*border) #add borders as an offset
offset=size/2-trans(box.center()) #offset in pixel coordinates
trans=trans*Trans(offset=offset.xy)
trans=trans*Xscale(1,-1) #invert y axis
trans=trans*Xlate(0,size.y) #origin is lower left corner
img = Image.new("RGB", map(rint,size.xy), back)
self._draw(ImageDraw.Draw(img), self.entities(), trans, pen)
if antialias>1:
size=size/antialias
img=img.resize(map(rint,size.xy), Image.ANTIALIAS)
return img
def img2base64(img,fmt='PNG'):
"""
:param img: :class:`PIL:Image`
:result: string base64 encoded image content in specified format
:see: http://stackoverflow.com/questions/14348442/django-how-do-i-display-a-pil-image-object-in-a-template
"""
output = StringIO.StringIO()
img.save(output, fmt)
output.seek(0)
output_s = output.read()
return base64.b64encode(output_s)
if __name__ == '__main__':
dxf=DXF("..\\tests\\FERRO_01.DXF")
img=dxf.img(size=[1280,None],border=50)
print img2base64(img)
img.save('..\\tests\\out.png')
extract all the details you need using ezdxf library.
using matplotlib library plot them as graph using matplotlib commands.
save the file as you need using same matplotlib library.

Python 2.6 xml.dom.ext Object Missing?

I'm using a script I found online to convert some files through parsing some XML. The script was built in Python 2.6 and it's using a module that I believe doesn't come with 2.6 through what I've read on the web. I'm wondering if there's a work around. The error I am getting is:
No Module name EXT
In the following script, I think it's getting hung up on import xml.dom.ext and it only seems to use this object at the very end to PrettyPrint (See the very last Try statement) I'm wondering if there's a workaround for this in 2.6? I can't seem to find a module that contains the EXT object which I can import.
The script is:
from xml.dom.minidom import Document
import xml.dom.ext
import string
import os
import arcpy
#Read input parameters from GP dialog
output = arcpy.GetParameterAsText(0)
#Create an output qgs file
f = open(output, "w")
# Create the minidom
doc = Document()
# Create the <qgis> base element
qgis = doc.createElement("qgis")
qgis.setAttribute("projectname", " ")
qgis.setAttribute("version", "1.6.0-Capiapo")
doc.appendChild(qgis)
# Create the <title> element
title = doc.createElement("title")
qgis.appendChild(title)
# Assign current document
mxd = arcpy.mapping.MapDocument("CURRENT")
print 'Converting mxd........'
# Dataframe elements
df = arcpy.mapping.ListDataFrames(mxd)[0]
unit = doc.createTextNode(df.mapUnits)
xmin1 = doc.createTextNode(str(df.extent.XMin))
ymin1 = doc.createTextNode(str(df.extent.YMin))
xmax1 = doc.createTextNode(str(df.extent.XMax))
ymax1 = doc.createTextNode(str(df.extent.YMax))
# srsid = doc.createTextNode
srid1 = doc.createTextNode(str(df.spatialReference.factoryCode))
srid2 = doc.createTextNode(str(df.spatialReference.factoryCode))
epsg1 = doc.createTextNode(str(df.spatialReference.factoryCode))
epsg2 = doc.createTextNode(str(df.spatialReference.factoryCode))
description1 = doc.createTextNode(str(df.spatialReference.name))
description2 = doc.createTextNode(str(df.spatialReference.name))
ellipsoidacronym1 = doc.createTextNode(str(df.spatialReference.name))
ellipsoidacronym2 = doc.createTextNode(str(df.spatialReference.name))
geographicflag1 = doc.createTextNode("true")
geographicflag2 = doc.createTextNode("true")
authid2 = doc.createTextNode("EPSG:"+str(df.spatialReference.factoryCode))
authid3 = doc.createTextNode("EPSG:"+str(df.spatialReference.factoryCode))
# Layerlist elements
lyrlist = arcpy.mapping.ListLayers(df)
count1 = str(len(lyrlist))
# mapcanvas
def map_canvas():
# Create the <mapcanvas> element
mapcanvas = doc.createElement("mapcanvas")
qgis.appendChild(mapcanvas)
# Create the <units> element
units = doc.createElement("units")
units.appendChild(unit)
mapcanvas.appendChild(units)
# Create the <extent> element
extent = doc.createElement("extent")
mapcanvas.appendChild(extent)
# Create the <xmin> element
xmin = doc.createElement("xmin")
xmin.appendChild(xmin1)
extent.appendChild(xmin)
# Create the <ymin> element
ymin = doc.createElement("ymin")
ymin.appendChild(ymin1)
extent.appendChild(ymin)
# Create the <xmax> element
xmax = doc.createElement("xmax")
xmax.appendChild(xmax1)
extent.appendChild(xmax)
# Create the <ymax> element
ymax = doc.createElement("ymax")
ymax.appendChild(ymax1)
extent.appendChild(ymax)
# Create the <projections> element
projections = doc.createElement("projections")
mapcanvas.appendChild(projections)
# Create the <destinationsrs> element
destinationsrs = doc.createElement("destinationsrs")
mapcanvas.appendChild(destinationsrs)
# Create the <spatialrefsys> element
spatialrefsys = doc.createElement("spatialrefsys")
destinationsrs.appendChild(spatialrefsys)
# Create the <proj4> element
proj4 = doc.createElement("proj4")
spatialrefsys.appendChild(proj4)
# Create the <srsid> element
srsid = doc.createElement("srsid")
spatialrefsys.appendChild(srsid)
# Create the <srid> element
srid = doc.createElement("srid")
srid.appendChild(srid1)
spatialrefsys.appendChild(srid)
# Create the <authid> element
authid = doc.createElement("authid")
authid.appendChild(authid2)
spatialrefsys.appendChild(authid)
# Create the <description> element
description = doc.createElement("description")
description.appendChild(description1)
spatialrefsys.appendChild(description)
# Create the <projectionacronym> element
projectionacronym = doc.createElement("projectionacronym")
spatialrefsys.appendChild(projectionacronym)
# Create the <ellipsoidacronym element
ellipsoidacronym = doc.createElement("ellipsoidacronym")
ellipsoidacronym.appendChild(ellipsoidacronym1)
spatialrefsys.appendChild(ellipsoidacronym)
# Create the <geographicflag> element
geographicflag = doc.createElement("geographicflag")
geographicflag.appendChild(geographicflag1)
spatialrefsys.appendChild(geographicflag)
# Legend
def legend_func():
# Create the <legend> element
legend = doc.createElement("legend")
qgis.appendChild(legend)
for lyr in lyrlist:
if(lyr.isGroupLayer == False):
# Create the <legendlayer> element
legendlayer = doc.createElement("legendlayer")
legendlayer.setAttribute("open", "true")
legendlayer.setAttribute("checked", "Qt::Checked")
legendlayer.setAttribute("name",str(lyr.name))
legend.appendChild(legendlayer)
# Create the <filegroup> element
filegroup = doc.createElement("filegroup")
filegroup.setAttribute("open", "true")
filegroup.setAttribute("hidden", "false")
legendlayer.appendChild(filegroup)
# Create the <legendlayerfile> element
legendlayerfile = doc.createElement("legendlayerfile")
legendlayerfile.setAttribute("isInOverview", "0")
legendlayerfile.setAttribute("layerid", str(lyr.name)+str(20110427170816078))
legendlayerfile.setAttribute("visible", "1")
filegroup.appendChild(legendlayerfile)
# Project Layers
def project_layers():
# Create the <projectlayers> element
projectlayers = doc.createElement("projectlayers")
projectlayers.setAttribute("layercount", count1)
qgis.appendChild(projectlayers)
for lyr in lyrlist:
if(lyr.isGroupLayer == False and lyr.isRasterLayer == False):
geometry1 = arcpy.Describe(lyr)
geometry2 = str(geometry1.shapeType)
ds = doc.createTextNode(str(lyr.dataSource))
name1 = doc.createTextNode(str(lyr.name)+str(20110427170816078))
name2 = doc.createTextNode(str(lyr.name))
# Create the <maplayer> element
maplayer = doc.createElement("maplayer")
maplayer.setAttribute("minimumScale", "0")
maplayer.setAttribute("maximumScale", "1e+08")
maplayer.setAttribute("minLabelScale", "0")
maplayer.setAttribute("maxLabelScale", "1e+08")
maplayer.setAttribute("geometry", geometry2)
if(lyr.isRasterLayer == True):
maplayer.setAttribute("type", "raster")
else:
maplayer.setAttribute("type", "vector")
maplayer.setAttribute("hasScaleBasedVisibilityFlag", "0")
maplayer.setAttribute("scaleBasedLabelVisibilityFlag", "0")
projectlayers.appendChild(maplayer)
# Create the <id> element
id = doc.createElement("id")
id.appendChild(name1)
maplayer.appendChild(id)
# Create the <datasource> element
datasource = doc.createElement("datasource")
datasource.appendChild(ds)
maplayer.appendChild(datasource)
# Create the <layername> element
layername = doc.createElement("layername")
layername.appendChild(name2)
maplayer.appendChild(layername)
# Create the <srs> element
srs = doc.createElement("srs")
maplayer.appendChild(srs)
# Create the <spatialrefsys> element
spatialrefsys = doc.createElement("spatialrefsys")
srs.appendChild(spatialrefsys)
# Create the <proj4> element
proj4 = doc.createElement("proj4")
spatialrefsys.appendChild(proj4)
# Create the <srsid> element
srsid = doc.createElement("srsid")
spatialrefsys.appendChild(srsid)
# Create the <srid> element
srid = doc.createElement("srid")
srid.appendChild(srid2)
spatialrefsys.appendChild(srid)
# Create the <authid> element
authid = doc.createElement("authid")
authid.appendChild(authid3)
spatialrefsys.appendChild(authid)
# Create the <description> element
description = doc.createElement("description")
description.appendChild(description2)
spatialrefsys.appendChild(description)
# Create the <projectionacronym> element
projectionacronym = doc.createElement("projectionacronym")
spatialrefsys.appendChild(projectionacronym)
# Create the <ellipsoidacronym element
ellipsoidacronym = doc.createElement("ellipsoidacronym")
ellipsoidacronym.appendChild(ellipsoidacronym2)
spatialrefsys.appendChild(ellipsoidacronym)
# Create the <geographicflag> element
geographicflag = doc.createElement("geographicflag")
geographicflag.appendChild(geographicflag2)
spatialrefsys.appendChild(geographicflag)
# Create the <transparencyLevelInt> element
transparencyLevelInt = doc.createElement("transparencyLevelInt")
transparency2 = doc.createTextNode("255")
transparencyLevelInt.appendChild(transparency2)
maplayer.appendChild(transparencyLevelInt)
# Create the <customproperties> element
customproperties = doc.createElement("customproperties")
maplayer.appendChild(customproperties)
# Create the <provider> element
provider = doc.createElement("provider")
provider.setAttribute("encoding", "System")
ogr = doc.createTextNode("ogr")
provider.appendChild(ogr)
maplayer.appendChild(provider)
# Create the <singlesymbol> element
singlesymbol = doc.createElement("singlesymbol")
maplayer.appendChild(singlesymbol)
# Create the <symbol> element
symbol = doc.createElement("symbol")
singlesymbol.appendChild(symbol)
# Create the <lowervalue> element
lowervalue = doc.createElement("lowervalue")
symbol.appendChild(lowervalue)
# Create the <uppervalue> element
uppervalue = doc.createElement("uppervalue")
symbol.appendChild(uppervalue)
# Create the <label> element
label = doc.createElement("label")
symbol.appendChild(label)
# Create the <rotationclassificationfieldname> element
rotationclassificationfieldname = doc.createElement("rotationclassificationfieldname")
symbol.appendChild(rotationclassificationfieldname)
# Create the <scaleclassificationfieldname> element
scaleclassificationfieldname = doc.createElement("scaleclassificationfieldname")
symbol.appendChild(scaleclassificationfieldname)
# Create the <symbolfieldname> element
symbolfieldname = doc.createElement("symbolfieldname")
symbol.appendChild(symbolfieldname)
# Create the <outlinecolor> element
outlinecolor = doc.createElement("outlinecolor")
outlinecolor.setAttribute("red", "88")
outlinecolor.setAttribute("blue", "99")
outlinecolor.setAttribute("green", "37")
symbol.appendChild(outlinecolor)
# Create the <outlinestyle> element
outlinestyle = doc.createElement("outlinestyle")
outline = doc.createTextNode("SolidLine")
outlinestyle.appendChild(outline)
symbol.appendChild(outlinestyle)
# Create the <outlinewidth> element
outlinewidth = doc.createElement("outlinewidth")
width = doc.createTextNode("0.26")
outlinewidth.appendChild(width)
symbol.appendChild(outlinewidth)
# Create the <fillcolor> element
fillcolor = doc.createElement("fillcolor")
fillcolor.setAttribute("red", "90")
fillcolor.setAttribute("blue", "210")
fillcolor.setAttribute("green", "229")
symbol.appendChild(fillcolor)
# Create the <fillpattern> element
fillpattern = doc.createElement("fillpattern")
fill = doc.createTextNode("SolidPattern")
fillpattern.appendChild(fill)
symbol.appendChild(fillpattern)
# Create the <texturepath> element
texturepath = doc.createElement("texturepath")
texturepath.setAttribute("null", "1")
symbol.appendChild(texturepath)
map_canvas()
legend_func()
project_layers()
# Write to qgis file
try:
xml.dom.ext.PrettyPrint(doc, f)
finally:
f.close()
print 'Done'
The xml.dom.ext module was never added to the Python standard library.
It was only ever part of the PyXML distribution, but that has not seen any updates in years and I doubt it'll still work on Python 2.6.
Instead, just call the minidom .toprettyxml() method on your document to pretty print the output, then write that data out to the file:
f.write(doc.toprettyxml())

Categories

Resources