最近新接的活,第一個任務是處理一堆xml格式的專利文件,把裏面的有效信息提取出來python
由於公司的相關規定不容許把文件down到本地處理,只能在對方提供的遠程服務器上寫代碼linux
因爲xml裏面的元素是XXX:YYYY這種帶前綴的格式,用xml.etree的ElementTree死活解析不出來,最後從OverStack上找到了解釋express
ElementTree is not too smart about namespaces. You need to give the .find()
, findall()
and iterfind()
methods an explicit namespace dictionary. This is not documented very well:服務器
namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed root.findall('owl:Class', namespaces)
Prefixes are only looked up in the namespaces
parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl:
part, looks up the corresponding namespace URL in the namespaces
dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class
instead.python2.7
If you can switch to the lxml
library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap
attribute on elements.spa
因而果斷去裝lxmlcode
服務器上已經裝了python2.7,然而除此以外的東西全都沒有,所以又手動裝了pipxml
執行pip install lxml 報了一大堆錯,注意到:ip
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?ci
查到lxml還須要先安裝依賴庫libxml2和libxslt的開發版
yum install libxml2-devel
yum install libxslt-devel
安裝好依賴庫後pip仍是報錯
此次又認真讀了一遍錯誤信息發現前面竟然還有一行:
unable to execute gcc: No such file or directory
好吧,連gcc都沒有安裝,難怪沒法編譯
yum install gcc
安裝好之後pip install,竟然,仍是報錯!
src/lxml/lxml.etree.c:84:20: 致命錯誤:Python.h:沒有那個文件或目錄
再查資料,原來還須要安裝一個python-devel,這是Python的頭文件和靜態庫包
yum install python-devel
安裝完以後再次pip install lxml
終於見到了喜聞樂見的
Successfully installed lxml
至此,linux下的lxml安裝完成