Tensorflow運行

1.FLAGS = tf.app.flags.FLAGS
執行main函數之前首先進行flags的解析,也就是說TensorFlow通過設置flags來傳遞tf.app.run()所需要的參數,我們可以直接在程序運行前初始化flags,也可以在運行程序的時候設置命令行參數來達到傳參的目的。

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')
flags.DEFINE_integer('epoch_number', None, 'Number of epochs to run trainer.')
flags.DEFINE_integer("thread_number", 10 , "Number of thread to read data")
flags.DEFINE_string("mode", "train", "Option mode: train, train_from_scratch, inference")

2.xml.etree.cElementTree
python 使用ElementTree解析xml
2.1 解析
1)調用parse()方法,返回解析樹
python3.3之後ElementTree模塊會自動尋找可用的C庫來加快速度

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET
tree = ET.parse("country.xml")  # <class 'xml.etree.ElementTree.ElementTree'>
root = tree.getroot()           # 獲取根節點 <Element 'data' at 0x02BF6A80>

2)調用from_string(),返回解析樹的根元素

import xml.etree.ElementTree as ET
data = open("country.xml").read()
root = ET.fromstring(data)   # <Element 'data' at 0x036168A0>

3)調用ElementTree類ElementTree(self, element=None, file=None) # 這裏的element作爲根節點

import xml.etree.ElementTree as ET
tree = ET.ElementTree(file="country.xml")  # <xml.etree.ElementTree.ElementTree object at 0x03031390>
root = tree.getroot()  # <Element 'data' at 0x030EA600>

2.2 遍歷
1)簡單遍歷

import xml.etree.ElementTree as ET

tree = ET.parse("country.xml")
root = tree.getroot()
print(root.tag, ":", root.attrib)  # 打印根元素的tag和屬性
#遍歷xml文檔的第二層
for child in root:
    # 第二層節點的標籤名稱和屬性
    print(child.tag,":", child.attrib) 
    # 遍歷xml文檔的第三層
    for children in child:
        # 第三層節點的標籤名稱和屬性
        print(children.tag, ":", children.attrib)

可以通過下標的方式直接訪問節點
訪問根節點下第一個country的第二個節點year,獲取對應的文本
year = root[0][1].text # 2008

2)ElementTree提供的方法


find(match) # 查找第一個匹配的子元素, match可以時tag或是xpaht路徑
findall(match) # 返回所有匹配的子元素列表
findtext(match, default=None) #
iter(tag=None) # 以當前元素爲根節點 創建樹迭代器,如果tag不爲None,則以tag進行過濾
iterfind(match) #

例子:

#過濾出所有neighbor標籤
for neighbor in root.iter("neighbor"):
    print(neighbor.tag, ":", neighbor.attrib)
#遍歷所有的counry標籤
for country in root.findall("country"):
    # 查找country標籤下的第一個rank標籤
    rank = country.find("rank").text
    # 獲取country標籤的name屬性
    name = country.get("name")
    print(name, rank)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章