本文整理汇总了Python中future.utils.iteritems方法的典型用法代码示例。如果您正苦于以下问题:Python utils.iteritems方法的具体用法?Python utils.iteritems怎么用?Python utils.iteritems使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类future.utils
的用法示例。
在下文中一共展示了utils.iteritems方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: lists_by_context
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def lists_by_context(self, context, break_on_first=False):
"""Return a generator expression that iterates over all video
lists with the given context.
Will match any video lists with type contained in context
if context is a list."""
# 'context' may contain a list of multiple contexts or a single
# 'context' can be passed as a string, convert to simplify code
if not isinstance(context, list):
context = [context]
match_context = ((lambda context, contexts: context in contexts)
if isinstance(context, list)
else (lambda context, target: context == target))
# Keep sort order of context list
lists = {}
for context_name in context:
for list_id, video_list in iteritems(self.lists):
if match_context(video_list['context'], context_name):
lists.update({list_id: VideoList(self.data, list_id)})
if break_on_first:
break
return iteritems(lists)
示例2: iterate_references
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def iterate_references(source):
"""Generator expression that iterates over a dictionary of
index=>reference pairs (sorted in ascending order by indices) until it
reaches the first empty reference, which signals the end of the reference
list.
Items with a key that do not represent an integer are ignored."""
for index, ref in sorted({int(k): v
for k, v in iteritems(source)
if common.is_numeric(k)}.items()):
path = reference_path(ref)
if path is None:
break
if path[0] == 'characters':
# TODO: Implement handling of character references in Kids profiles
continue
yield (index, path)
示例3: _convert_dict_to_listitem
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def _convert_dict_to_listitem(dict_item):
list_item = xbmcgui.ListItem(label=dict_item['label'], offscreen=True)
list_item.setContentLookup(False)
properties = dict_item.get('properties', {}) # 'properties' key allow to set custom properties to xbmcgui.Listitem
properties['isFolder'] = str(dict_item['is_folder'])
if not dict_item['is_folder'] and dict_item['media_type'] in [common.VideoId.EPISODE,
common.VideoId.MOVIE,
common.VideoId.SUPPLEMENTAL]:
properties.update({
'IsPlayable': 'true',
'TotalTime': dict_item.get('TotalTime', ''),
'ResumeTime': dict_item.get('ResumeTime', '')
})
for stream_type, quality_info in iteritems(dict_item.get('quality_info', {})):
list_item.addStreamInfo(stream_type, quality_info)
list_item.setProperties(properties)
list_item.setInfo('video', dict_item.get('info', {}))
list_item.setArt(dict_item.get('art', {}))
list_item.addContextMenuItems(dict_item.get('menu_items', []))
if dict_item.get('is_selected'):
list_item.select(True)
return list_item
示例4: elements
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def elements(self):
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
If an element's count has been set to zero or is a negative number,
elements() will ignore it.
'''
for elem, count in iteritems(self):
for _ in range(count):
yield elem
# Override dict methods where the meaning changes for Counter objects.
示例5: get_entities_iterators
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def get_entities_iterators(intent_entities, language,
add_builtin_entities_examples, random_state):
from snips_nlu_parsers import get_builtin_entity_examples
entities_its = dict()
for entity_name, entity in iteritems(intent_entities):
utterance_values = random_state.permutation(sorted(entity[UTTERANCES]))
if add_builtin_entities_examples and is_builtin_entity(entity_name):
entity_examples = get_builtin_entity_examples(
entity_name, language)
# Builtin entity examples must be kept first in the iterator to
# ensure that they are used when augmenting data
iterator_values = entity_examples + list(utterance_values)
else:
iterator_values = utterance_values
entities_its[entity_name] = cycle(iterator_values)
return entities_its
示例6: log_weights
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def log_weights(self):
"""Returns a logs for both the label-to-label and label-to-features
weights"""
if not self.slot_name_mapping:
return "No weights to display: intent '%s' has no slots" \
% self.intent
log = ""
transition_features = self.crf_model.transition_features_
transition_features = sorted(
iteritems(transition_features), key=_weight_absolute_value,
reverse=True)
log += "\nTransition weights: \n\n"
for (state_1, state_2), weight in transition_features:
log += "\n%s %s: %s" % (
_decode_tag(state_1), _decode_tag(state_2), weight)
feature_weights = self.crf_model.state_features_
feature_weights = sorted(
iteritems(feature_weights), key=_weight_absolute_value,
reverse=True)
log += "\n\nFeature weights: \n\n"
for (feat, tag), weight in feature_weights:
log += "\n%s %s: %s" % (feat, _decode_tag(tag), weight)
return log
示例7: feature_index_to_feature_name
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def feature_index_to_feature_name(self):
"""Maps the feature index of the feature matrix to printable features
names. Mainly useful for debug.
Returns:
dict: a dict mapping feature indices to printable features names
"""
if not self.fitted:
return dict()
index = {
i: "ngram:%s" % ng
for ng, i in iteritems(self.tfidf_vectorizer.vocabulary)
}
num_ng = len(index)
if self.cooccurrence_vectorizer is not None:
for word_pair, j in iteritems(
self.cooccurrence_vectorizer.word_pairs):
index[j + num_ng] = "pair:%s+%s" % (word_pair[0], word_pair[1])
return index
示例8: persist
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def persist(self, path):
path.mkdir()
builtin_entity_scope = None
if self.builtin_entity_scope is not None:
builtin_entity_scope = list(self.builtin_entity_scope)
self_as_dict = {
"language_code": self.language,
"word_pairs": {
i: list(p) for p, i in iteritems(self.word_pairs)
},
"builtin_entity_scope": builtin_entity_scope,
"config": self.config.to_dict()
}
vectorizer_json = json_string(self_as_dict)
vectorizer_path = path / "vectorizer.json"
with vectorizer_path.open(mode="w", encoding="utf8") as f:
f.write(vectorizer_json)
self.persist_metadata(path)
示例9: from_dict
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def from_dict(cls, dict):
if dict is None:
return cls()
params = inspect.signature(cls.__init__).parameters
if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in
params.values()):
return cls(**dict)
param_names = set()
for i, (name, param) in enumerate(iteritems(params)):
if i == 0 and name == "self":
continue
if param.kind in KEYWORD_KINDS:
param_names.add(name)
filtered_dict = {k: v for k, v in iteritems(dict) if k in param_names}
return cls(**filtered_dict)
示例10: to_dict
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def to_dict(self):
"""Returns a json-serializable dict"""
stop_words_whitelist = None
if self._stop_words_whitelist is not None:
stop_words_whitelist = {
intent: sorted(values)
for intent, values in iteritems(self._stop_words_whitelist)}
return {
"config": self.config.to_dict(),
"language_code": self.language,
"map": self._map,
"slots_names": self._slots_names,
"intents_names": self._intents_names,
"entity_scopes": self._entity_scopes,
"stop_words_whitelist": stop_words_whitelist,
}
示例11: frameAllNodes
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def frameAllNodes(self):
allnodes = []
for name, node in iteritems(self.__nodes):
allnodes.append(node)
self.frameNodes(allnodes)
示例12: _to_xml
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement("row", {})
self._to_xml(xml, item)
xml.endElement("row")
elif isinstance(data, dict):
for key, value in iteritems(data):
key = key.replace(' ', '_')
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)
else:
xml.characters(smart_text(data))
示例13: load_cfg
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def load_cfg(cfg_to_load):
"""Wrapper around yaml.load used for maintaining backward compatibility"""
file_types = [file, io.IOBase] if six.PY2 else [io.IOBase] # noqa false positive
expected_types = tuple(file_types + list(six.string_types))
assert isinstance(cfg_to_load, expected_types), \
'Expected one of {}, got {}'.format(expected_types, type(cfg_to_load))
if isinstance(cfg_to_load, tuple(file_types)):
cfg_to_load = ''.join(cfg_to_load.readlines())
for old_module, new_module in iteritems(_RENAMED_MODULES):
# yaml object encoding: !!python/object/new:<module>.<object>
old_module, new_module = 'new:' + old_module, 'new:' + new_module
cfg_to_load = cfg_to_load.replace(old_module, new_module)
# Import inline due to a circular dependency between env.py and config.py
import detectron.utils.env as envu
return envu.yaml_load(cfg_to_load)
示例14: parse_params
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def parse_params(indict, *specs):
if not specs:
specs = [NIF_PARAMS]
logger.debug("Parsing: {}\n{}".format(indict, specs))
outdict = indict.copy()
wrong_params = {}
for spec in specs:
for param, options in iteritems(spec):
for alias in options.get("aliases", []):
# Replace each alias with the correct name of the parameter
if alias in indict and alias != param:
outdict[param] = indict[alias]
del outdict[alias]
break
if param not in outdict:
if "default" in options:
# We assume the default is correct
outdict[param] = options["default"]
elif options.get("required", False):
wrong_params[param] = spec[param]
continue
if 'processor' in options:
outdict[param] = processors[options['processor']](outdict[param])
if "options" in options:
if options["options"] == boolean:
outdict[param] = str(outdict[param]).lower() in ['true', '1', '']
elif outdict[param] not in options["options"]:
wrong_params[param] = spec[param]
if wrong_params:
logger.debug("Error parsing: %s", wrong_params)
message = Error(
status=400,
message='Missing or invalid parameters',
parameters=outdict,
errors=wrong_params)
raise message
return outdict
示例15: run_device_tensor_initializations
# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import iteritems [as 别名]
def run_device_tensor_initializations(self):
for device_tensor_view, host_tensor in iteritems(self.device_initializations):
device_tensor_view[()] = host_tensor
self.device_initializations = dict()