Python-text-processing-python-pretty-prints

提供:Dev Guides
移動先:案内検索

Python-数字をきれいに印刷

Pythonモジュール pprint は、Pythonのさまざまなデータオブジェクトに適切な印刷形式を与えるために使用されます。 これらのデータオブジェクトは、辞書データタイプ、またはJSONデータを含むデータオブジェクトを表すことができます。 以下の例では、pprintモジュールを適用する前と適用した後のデータの外観を確認します。

import pprint

student_dict = {'Name': 'Tusar', 'Class': 'XII',
     'Address': {'FLAT ':1308, 'BLOCK ':'A', 'LANE ':2, 'CITY ': 'HYD'}}

print student_dict
print "\n"
print "***With Pretty Print***"
print "-----------------------"
pprint.pprint(student_dict,width=-1)

上記のプログラムを実行すると、次の出力が得られます-

{'Address': {'FLAT ': 1308, 'LANE ': 2, 'CITY ': 'HYD', 'BLOCK ': 'A'}, 'Name': 'Tusar', 'Class': 'XII'}


***With Pretty Print***
-----------------------
{'Address': {'BLOCK ': 'A',
             'CITY ': 'HYD',
             'FLAT ': 1308,
             'LANE ': 2},
 'Class': 'XII',
 'Name': 'Tusar'}

JSONデータの処理

Pprintは、JSONデータをより読みやすい形式にフォーマットすることで処理することもできます。

import pprint

emp = {"Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
   "Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],
   "StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
      "7/30/2013","6/17/2014"],
   "Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"] }

x= pprint.pformat(emp, indent=2)
print x

上記のプログラムを実行すると、次の出力が得られます-

{ 'Dept': [ 'IT',
            'Operations',
            'IT',
            'HR',
            'Finance',
            'IT',
            'Operations',
            'Finance'],
  'Name': ['Rick', 'Dan', 'Michelle', 'Ryan', 'Gary', 'Nina', 'Simon', 'Guru'],
  'Salary': [ '623.3',
              '515.2',
              '611',
              '729',
              '843.25',
              '578',
              '632.8',
              '722.5'],
  'StartDate': [ '1/1/2012',
                 '9/23/2013',
                 '11/15/2014',
                 '5/11/2014',
                 '3/27/2015',
                 '5/21/2013',
                 '7/30/2013',
                 '6/17/2014']}