当前位置: 首页>>代码示例>>Python>>正文


Python pprint.pprint方法代码示例

本文整理汇总了Python中pprint.pprint方法的典型用法代码示例。如果您正苦于以下问题:Python pprint.pprint方法的具体用法?Python pprint.pprint怎么用?Python pprint.pprint使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块pprint的用法示例。

在下文中一共展示了pprint.pprint方法的26个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def main():
    global output_file
    num_args = len(sys.argv)
    if num_args < 3:
        print("usage: %s <json-file-1> [json-file-2 ...] <output-csv-file>" % sys.argv[0], file=sys.stderr)
        exit(1)

    json_files = sys.argv[1:num_args - 1]
    output_file = sys.argv[num_args - 1]

    merged_json_data = {}
    for json_file in json_files:
        print("> reading JSON file '%s'..." % json_file)
        with open(json_file) as f:
            json_data = json.load(f)
            for label, data in json_data.items():
                if label not in merged_json_data:
                    merged_json_data[label] = data
                else:
                    merged_json_data[label]['data'].extend(data['data'])

    # pprint(merged_json_data)
    analyse(merged_json_data) 
开发者ID:internaut,项目名称:facebook-discussion-tk,代码行数:25,代码来源:analyze_noun_counts.py


示例2: import_daily_schedule

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def import_daily_schedule(self):

        """Dropping previous Daily Schedule table before adding the imported data"""
        self.db.remove_all_daily_scheduled_items()
        with open('pseudo-daily_schedule.json') as data_file:    
            data = json.load(data_file)
        #pprint(data)
        for row in data:
            """print row"""
            self.db.import_daily_schedule_table_by_row(
                row[2], 
                row[3], 
                row[4], 
                row[5], 
                row[6], 
                row[7], 
                row[8], 
                row[9], 
                row[10], 
                row[11], 
                row[12],
                row[13],
            )
        print "+++++ Done. Imported Daily Schedule." 
开发者ID:justinemter,项目名称:pseudo-channel,代码行数:26,代码来源:PseudoChannel.py


示例3: pos_pyscf

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def pos_pyscf ():
    '''converts ase position lists to a long string which is readable for Pyscf'''
    import re        
    import pprint
    for k in sorted (data.keys()):
            nn=sum(1 for c in data[k]['symbols'] if c.isupper()) #number of atoms
            a=re.findall('[A-Z][^A-Z]*', data[k]['symbols']) #atom index e.g. a=['H','Al','Cl']
            num=[]        
            for i in range(len(data[k]['positions'])):
                pos= (str(data[k]['positions'][i]).strip('[]'))
                pos = a[i]+' '+pos
                if (i!= (len(data[k]['positions'])-1)): pos=pos+';'
                num.append(pos)
            pos_py=" " .join(map(str,num))
            data[k]['position_pyscf']=pos_py
    pprint.pprint(data) 
开发者ID:pyscf,项目名称:pyscf,代码行数:18,代码来源:m_g297.py


示例4: train

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def train(config):
    c = Classifier.classifier(config)
    pprint.pprint(c.tuples.all_tuples)
    print('All tuples:',len(c.tuples.all_tuples))
    model_path = config.get("train", "output")
    model_dir = os.path.dirname(model_path)
    if not os.path.exists(model_dir):
        os.makedirs(model_dir)
    print('output to {}'.format(model_path))
    dataroot = config.get("train", "dataroot")
    dataset = config.get("train", "dataset")
    dw = sutils.dataset_walker(dataset = dataset, dataroot=dataroot, labels=True)
    c = Classifier.classifier(config)
    c.cacheFeature(dw)
    c.train(dw)
    c.save(model_path)
    with zipfile.ZipFile(os.path.join(model_dir, 'svm_multiwoz.zip'), 'w', zipfile.ZIP_DEFLATED) as zf:
        zf.write(model_path) 
开发者ID:ConvLab,项目名称:ConvLab,代码行数:20,代码来源:train.py


示例5: parse

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def parse(self, utterance, context=[]):
        """
        Predict the dialog act of a natural language utterance and apply error model.
        Args:
            utterance (str): A natural language utterance.
        Returns:
            output (dict): The dialog act of utterance.
        """
        # print("nlu input:")
        # pprint(utterance)

        if len(utterance) == 0:
            return {}

        tokens = self.tokenizer.split_words(utterance)
        instance = self.dataset_reader.text_to_instance(tokens)
        outputs = self.model.forward_on_instance(instance)

        return outputs["dialog_act"] 
开发者ID:ConvLab,项目名称:ConvLab,代码行数:21,代码来源:nlu.py


示例6: mark_not_mentioned

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def mark_not_mentioned(state):
    for domain in state:
        # if domain == 'history':
        if domain not in ['police', 'hospital', 'taxi', 'train', 'attraction', 'restaurant', 'hotel']:
            continue
        try:
            # if len([s for s in state[domain]['semi'] if s != 'book' and state[domain]['semi'][s] != '']) > 0:
                # for s in state[domain]['semi']:
                #     if s != 'book' and state[domain]['semi'][s] == '':
                #         state[domain]['semi'][s] = 'not mentioned'
            for s in state[domain]['semi']:
                if state[domain]['semi'][s] == '':
                    state[domain]['semi'][s] = 'not mentioned'
        except Exception as e:
            # print(str(e))
            # pprint(state[domain])
            pass 
开发者ID:ConvLab,项目名称:ConvLab,代码行数:19,代码来源:policy.py


示例7: test_status_update

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def test_status_update(self, path1):
        # not a mark because the global "pytestmark" will end up overwriting a mark here
        pytest.xfail("svn-1.7 has buggy 'status --xml' output")
        r = path1
        try:
            r.update(rev=1)
            s = r.status(updates=1, rec=1)
            # Comparing just the file names, because paths are unpredictable
            # on Windows. (long vs. 8.3 paths)
            import pprint
            pprint.pprint(s.allpath())
            assert r.join('anotherfile').basename in [item.basename for
                                                    item in s.update_available]
            #assert len(s.update_available) == 1
        finally:
            r.update() 
开发者ID:pytest-dev,项目名称:py,代码行数:18,代码来源:test_svnwc.py


示例8: _get_pretty_string

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def _get_pretty_string(obj):
    """Return a prettier version of obj

    Parameters
    ----------
    obj : object
        Object to pretty print

    Returns
    -------
    s : str
        Pretty print object repr
    """
    sio = StringIO()
    pprint.pprint(obj, stream=sio)
    return sio.getvalue() 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:18,代码来源:scope.py


示例9: get_named_entities

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def get_named_entities(en_doc):
    prop_noun_entities = {}
    prop_noun_entities_pos = {}
    payload = {}
    i = 0
    for ent in en_doc.ents:
        prop_noun_entities_pos[ent.text] = ent.start
        if i < 10:
            payload["name["+str(i)+"]"] = ent.text
            print(ent.label_, ent.text)
        if i == 9:
            prop_noun_entities = get_gender(payload, prop_noun_entities)
            i = 0
        i += 1
    pprint(payload)
    if i < 10:
        prop_noun_entities = get_gender(payload, prop_noun_entities)
    return prop_noun_entities, prop_noun_entities_pos 
开发者ID:5hirish,项目名称:adam_qas,代码行数:20,代码来源:anaphora_res.py


示例10: get_daily_schedule_cache_as_json

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def get_daily_schedule_cache_as_json(self):

        data = []
        try:
            with open('../.pseudo-cache/daily-schedule.json') as data_file:    
                data = json.load(data_file)
            #pprint(data)
        except IOError:
            print ("----- Having issues opening the pseudo-cache file.")
        return data 
开发者ID:justinemter,项目名称:pseudo-channel,代码行数:12,代码来源:PseudoChannel.py


示例11: demo

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def demo():
    from en.parser.nltk_lite.corpora import ieer
    from itertools import islice
    from pprint import pprint

#    pprint(extract(75, ieer.raw()))
    pprint(extract(75, ieer.dictionary())) 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:9,代码来源:ieer.py


示例12: addBookingPointer

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def addBookingPointer(state, pointer_vector):
    """Add information about availability of the booking option."""
    # Booking pointer
    rest_vec = np.array([1, 0])
    if "book" in state['restaurant']:
        if "booked" in state['restaurant']['book']:
            if state['restaurant']['book']["booked"]:
                if "reference" in state['restaurant']['book']["booked"][0]:
                    rest_vec = np.array([0, 1])

    hotel_vec = np.array([1, 0])
    if "book" in state['hotel']:
        if "booked" in state['hotel']['book']:
            if state['hotel']['book']["booked"]:
                if "reference" in state['hotel']['book']["booked"][0]:
                    hotel_vec = np.array([0, 1])

    train_vec = np.array([1, 0])
    if "book" in state['train']:
        if "booked" in state['train']['book']:
            if state['train']['book']["booked"]:
                if "reference" in state['train']['book']["booked"][0]:
                    train_vec = np.array([0, 1])

    pointer_vector = np.append(pointer_vector, rest_vec)
    pointer_vector = np.append(pointer_vector, hotel_vec)
    pointer_vector = np.append(pointer_vector, train_vec)

    # pprint(pointer_vector)
    return pointer_vector 
开发者ID:ConvLab,项目名称:ConvLab,代码行数:32,代码来源:policy.py


示例13: _get_num_items

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def _get_num_items(self):
        num_items = 0
        goal = self.state
        for domain in goal:
            if domain == 'domain_ordering':
                continue
            if 'info' in goal[domain]:
                num_items += len(goal[domain]['info'])
            if 'reqt' in goal[domain]:
                num_items += len(goal[domain]['reqt'])
            if 'book' in goal[domain]:
                num_items += len(goal[domain]['book'])
        pprint(goal)
        print("Num of remaining items:", num_items)
        return num_items 
开发者ID:ConvLab,项目名称:ConvLab,代码行数:17,代码来源:worlds.py


示例14: test_repo

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def test_repo():
    r = requests.get(
        "http://localhost:5000/repos?keyword=natural+language+processing"
    )
    pprint.pprint(r.json()) 
开发者ID:prkumar,项目名称:uplink,代码行数:7,代码来源:Tests.py


示例15: test_users_for_repos

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def test_users_for_repos():
    r = requests.get(
        "http://localhost:5000/users/JustFollowUs/repo/Natural-Language-Processing"
    )
    pprint.pprint(r.json()) 
开发者ID:prkumar,项目名称:uplink,代码行数:7,代码来源:Tests.py


示例16: test_users_for_keyword

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def test_users_for_keyword():
    r = requests.get("http://localhost:5000/users?keyword=lstm")
    pprint.pprint(r.json()) 
开发者ID:prkumar,项目名称:uplink,代码行数:5,代码来源:Tests.py


示例17: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def main(args):
    check(pygsti)
    for k, v in found.items():
        print('{}:'.format(k))
        print('    ' + '\n    '.join(v))
    #pprint(data)
    return 0 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:9,代码来源:checkDocs.py


示例18: itemmeta

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def itemmeta(self):
        """Returns metadata for members of the collection.

        Makes a single roundtrip to the server, plus two more at most if
        the ``autologin`` field of :func:`connect` is set to ``True``.

        :return: A :class:`splunklib.data.Record` object containing the metadata.

        **Example**::

            import splunklib.client as client
            import pprint
            s = client.connect(...)
            pprint.pprint(s.apps.itemmeta())
            {'access': {'app': 'search',
                                    'can_change_perms': '1',
                                    'can_list': '1',
                                    'can_share_app': '1',
                                    'can_share_global': '1',
                                    'can_share_user': '1',
                                    'can_write': '1',
                                    'modifiable': '1',
                                    'owner': 'admin',
                                    'perms': {'read': ['*'], 'write': ['admin']},
                                    'removable': '0',
                                    'sharing': 'user'},
             'fields': {'optional': ['author',
                                        'configured',
                                        'description',
                                        'label',
                                        'manageable',
                                        'template',
                                        'visible'],
                                        'required': ['name'], 'wildcard': []}}
        """
        response = self.get("_new")
        content = _load_atom(response, MATCH_ENTRY_CONTENT)
        return _parse_atom_metadata(content) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:40,代码来源:client.py


示例19: __init__

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def __init__(self):
        """天气预报,使用方法
        >>>import jtyoui
        >>>import pprint
        >>>w = jtyoui.WeatherForecast()
        >>>w.set_city('九龙')
        >>>pprint.pprint(w.get_today_weather())  # 获得当天 天气预报
        >>>pprint.pprint(w.get_7day_weather())  # 获得7天天气预报
        >>>pprint.pprint(w.get_15day_weather())  # 获得15天天气预报
        """
        self.weather = load_zip('city.zip', 'city.txt')
        self.codes = [] 
开发者ID:jtyoui,项目名称:Jtyoui,代码行数:14,代码来源:WeatherAddress.py


示例20: weather

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def weather(name, day):
    w = jtyoui.WeatherForecast()
    w.set_city(name)
    if day == 15:
        days = w.get_15day_weather()  # 获得当天 天气预报
    elif day == 7:
        days = w.get_7day_weather()  # 获得7天天气预报
    else:
        days = w.get_today_weather()  # 获得15天天气预报
    pprint.pprint(days) 
开发者ID:jtyoui,项目名称:Jtyoui,代码行数:12,代码来源:cli.py


示例21: pprint_for_ordereddict

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def pprint_for_ordereddict():
    """
    Context manager that causes pprint() to print OrderedDict objects as nicely
    as standard Python dictionary objects.
    """
    od_saved = OrderedDict.__repr__
    try:
        OrderedDict.__repr__ = dict.__repr__
        yield
    finally:
        OrderedDict.__repr__ = od_saved 
开发者ID:zhmcclient,项目名称:python-zhmcclient,代码行数:13,代码来源:get_inventory.py


示例22: extractObservables

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def extractObservables(args,indicators):
	 
	values = []

	for indicator in indicators:
		
		#Check if we were passed a list of indicators, or observables
		obs = indicator
		if "observable" in indicator:
			obs = indicator["observable"]
			
		try:
			if 'object' in obs:
				extractObservable( args, obs["object"], values )
			elif 'observable_composition' in obs:
				for observable in obs["observable_composition"]["observables"]:
					if 'object' in observable:
						extractObservable(args,observable["object"], values )

		except:
			
			print >> sys.stderr, "Could not handle observable/indicator:\n"
			pprint.pprint( indicator, sys.stderr )
			raise

	return values 
开发者ID:ibm-security-intelligence,项目名称:data-import,代码行数:28,代码来源:stix_import.py


示例23: pprint

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def pprint(self, *args, **kwargs):
        """Pretty-printer for parsed results as a list, using the C{pprint} module.
           Accepts additional positional or keyword args as defined for the 
           C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})"""
        pprint.pprint(self.asList(), *args, **kwargs)

    # add support for pickle protocol 
开发者ID:vulscanteam,项目名称:vulscan,代码行数:9,代码来源:pyparsing.py


示例24: default_main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def default_main(device_or_type, *coroutines):
    """ Simple, default main for FaceDancer emulation.

    Parameters:
        device_type -- The USBDevice type to emulate.
    """

    # Instantiate the relevant device, and connect it to our host.
    parser = argparse.ArgumentParser(description=f"Emulation frontend for {device_or_type.name}(s).")
    parser.add_argument('--print-only', action='store_true', help="Prints information about the device without emulating.")
    parser.add_argument('--suggest', action='store_true', help="Prints suggested code additions after device emualtion is complete.")
    parser.add_argument('-v', '--verbose', help="Controls verbosity. 0=silent, 3=default, 5=spammy", default=3)
    args = parser.parse_args()

    if sys.stdout.isatty():
        log_format = LOG_FORMAT_COLOR
    else:
        log_format = LOG_FORMAT_PLAIN

    # Set up our logging output.
    python_loglevel = 50 - (int(args.verbose) * 10)
    logging.basicConfig(level=python_loglevel, format=log_format)

    if inspect.isclass(device_or_type):
        device = device_or_type()
    else:
        device = device_or_type

    if args.print_only:
        pprint.pprint(device)
        sys.exit(0)

    # Run the relevant code, along with any added coroutines.
    device.emulate(*coroutines)

    if args.suggest:
        device.print_suggested_additions() 
开发者ID:usb-tools,项目名称:Facedancer,代码行数:39,代码来源:__init__.py


示例25: do_dump

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def do_dump(self, subcmd, opts, *dirs):
        """${cmd_name}: pprint the package changelog information

        ${cmd_usage}
        ${cmd_option_list}
        """
        pprint(self.readChangeLogs(dirs)) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:9,代码来源:factory-package-news.py


示例26: do_inspect

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pprint [as 别名]
def do_inspect(self, subcmd, opts, filename, package):
        """${cmd_name}: pprint the package changelog information

        ${cmd_usage}
        ${cmd_option_list}
        """
        f = open(filename, 'rb')
        (v, (pkgs, changelogs)) = pickle.load(
            f, encoding='utf-8', errors='backslashreplace')
        pprint(pkgs[package])
        pprint(changelogs[pkgs[package]['sourcerpm']]) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:13,代码来源:factory-package-news.py



注:本文中的pprint.pprint方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。