2016-07-12 29 views
-3
打印第10行,而不是整個列表

我試圖做到的是印刷10線改爲只使用pprint(dict(str_types))如何使用pprint

在這裏,整個名單是我的代碼

from collections import defaultdict 

str_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) 

expected = ["Street", "Avenue", "Boulevard", "Drive", "Court", "Place", "Square", "Lane", "Road", 
      "Trail", "Parkway", "Commons"] 

def audit_str_type(str_types, str_name, rex): 
    stn = rex.search(str_name) 
    if stn : 
     str_type = stn.group() 
     if str_type not in expected: 
      str_types[str_type].add(str_name) 

我定義了一個函數來審計標記元素,其中k =「addr:street」,並且任何標記元素都與is_str_name函數相匹配。

def audit(osmfile,rex): 
    osm_file = open(osmfile, "r", encoding="utf8") 
    str_types = defaultdict(set) 
    for event, elem in ET.iterparse(osm_file, events=("start",)): 

     if elem.tag == "node" or elem.tag == "way": 
      for tag in elem.iter("tag"): 
       if is_str_name(tag): 
        audit_str_type(str_types, tag.attrib['v'],rex) 

    return str_types 

在上面的代碼中,我使用「is_str_name」函數在調用審計函數來審計街道名稱時過濾標記。

def is_str_name(elem): 
    return (elem.attrib['k'] == "addr:street") 

str_types = audit(mydata, rex = str_type_re) 
pprint.pprint(dict(str_types[:10])) 
+0

加入'進口re'我'NameError後一個 [可驗證示例](http://stackoverflow.com/help/mcve),或者至少是您獲得的輸出和預期的輸出。 –

+0

'pprint.pprint(dict(str_types [:10]))'那有什麼問題,它看起來好像只能打印10.這真的需要[mcve]。 –

+0

@MorganThrapp'str_types'是一個'defaultdict',它不支持切片。 (但是,這是缺少一個MCVE) –

回答

0

使用pprint.pformat找回對象的字符串表示,而不是直接打印出來的,那麼你可以通過線分割了起來,只打印了前幾個:

whole_repr = pprint.pformat(dict(str_types)) 

for line in whole_repr.splitlines()[:10]: 
    print(line) 

注意,我無法測試這一點,因爲你沒有一個MCVE但我沒有一個更簡單的例子驗證:名稱「MYDATA」不defined`請提供:

>>> import pprint 
>>> thing = pprint.pformat({i:str(i) for i in range(10000)}) 
>>> type(thing), len(thing) 
(<class 'str'>, 147779) 
>>> for line in thing.splitlines()[:10]:print(line) 

{0: '0', 
1: '1', 
2: '2', 
3: '3', 
4: '4', 
5: '5', 
6: '6', 
7: '7', 
8: '8', 
9: '9', 
+0

我把它修好了 - 非常感謝 –