Python連載50-貪婪匹配、XPath介紹

1、貪婪和非貪婪node

1.貪婪:儘量多的匹配,(*)表示貪婪匹配git

2.非貪婪:找到符合條件的最小內容便可,(?)表示非貪婪github

3.正則默認使用貪婪匹配微信

 

import re

title = u"<div>name</div><div>age</div>"

p1 = re.compile(r"<div>.*</div>")#貪婪模式

p2 = re.compile(r"<div>.*?<div>")#非貪婪模式

m1 = p1.search(title)

print(m1.group())

​

m2 = p2.search(title)

print(m2.group())

 

2、XPATH工具

1.釋義:在XML文件中查找信息的一套規則/語言,根據XML的元素學習

文檔幫助:http://www.w3cshool.com.cn/xpath/index.asp開發工具

2.XPath開發工具大數據

開源的XPath表達式編輯工具:XMLQuireui

Chrome插件:XPath Helperspa

Firefox插件:XPath Checker

3.怎麼在XML文件中選取節點

(1)nodename:選取此節點的全部子節點

(2)/:從根節點開始選取

例子:/Student:沒有結果

/School:選取School節點

(3)//:選取節點,不考慮位置

例子://age:選取三個節點,通常組成列表返回

(4).:選取當前節點

(5)..:選取當前節點的父親節點

(6)@:選取屬性

(7)Xpath中查找通常按照路徑方法查找

School/teacher:返回teacher節點

School/student:返回兩個student節點

//Student:選取全部Student的節點,不考慮位置

School//Age:選取School後代中全部的Age節點

//@Other:選取Other屬性

//Age[@Details]:選取帶有屬性Details的Age元素

 

<?xml version="1.0" encoding="utf-8" ?>

<School>

    <Teacher desc="PythonTeacher" score="good">

        <name>LiuDana</name>

        <Age_1 Details="Age for year 2010">18</Age_1>

        <Mobile>13260446055</Mobile>

    </Teacher>

    <Student>

        <Name Other="他是班長">ZhangSan</Name>

        <Age Details="The youngest boy in class">14</Age>

    </Student>

    <Student>

        <Name>LiSi</Name>

        <Age>19</Age>

        <Mobile>15578875040</Mobile>

    </Student>

</School>

 

 

4.謂語

/School/Student[1]:選取School下面的第一個Student節點

/School/Student[last()]:選取School下面的最後一個Student節點

/School/Student[last()-1]:選取School下面的倒數第二個Student節點

/School/Student[position()<3]:選取School下面的前兩個節點

//Student[@score]:選取帶有屬性score的Student節點

//Student[@score="99"]:選取帶有屬性score而且屬性值爲99的Student節點

//Student[@score]/Age:選取帶有屬性score的Student節點的子節點Age

5.XPath中的一些操做

(1)|:或者

例如://Student[@score] | //Teacher:選取帶有屬性score的Student節點或者Teacher節點

(2)其他不常見的XPath運算符號包括+.-.*,div(除法的意思),>,<

2、源碼

D31_2_GreedMatch.py

D32_1_School.xml

https://github.com/ruigege66/Python_learning/blob/master/D31_2_GreedMatch.py

https://github.com/ruigege66/Python_learning/blob/master/D32_1_School.xml

2.CSDN:https://blog.csdn.net/weixin_44630050(心悅君兮君不知-睿)

3.博客園:https://www.cnblogs.com/ruigege0000/

4.歡迎關注微信公衆號:傅里葉變換,我的公衆號,僅用於學習交流,後臺回覆」禮包「,獲取大數據學習資料

 

相關文章
相關標籤/搜索