本文整理汇总了Python中types.StringTypes方法的典型用法代码示例。如果您正苦于以下问题:Python types.StringTypes方法的具体用法?Python types.StringTypes怎么用?Python types.StringTypes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类types
的用法示例。
在下文中一共展示了types.StringTypes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: similarity
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def similarity(self, v1, v2):
"""Return cosine similarity of given words or vectors.
If v1/v2 is a string, look up the corresponding word vector.
This is not particularly efficient function. Instead of many
invocations, consider word_similarity() or direct computation.
"""
vs = [v1, v2]
for i, v in enumerate(vs):
if isinstance(v, StringTypes):
v = self.word_to_unit_vector(v)
else:
v = v/numpy.linalg.norm(v) # costly but safe
vs[i] = v
return numpy.dot(vs[0], vs[1])
示例2: scopes_to_string
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def scopes_to_string(scopes):
"""Converts scope value to a string.
If scopes is a string then it is simply passed through. If scopes is an
iterable then a string is returned that is all the individual scopes
concatenated with spaces.
Args:
scopes: string or iterable of strings, the scopes.
Returns:
The scopes formatted as a single string.
"""
if isinstance(scopes, types.StringTypes):
return scopes
else:
return ' '.join(scopes)
示例3: make_fancy_blob
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def make_fancy_blob(self, name, timestamp_seconds, value):
"""Makes a blob containing "name", "timestamp" and "value" attributes.
Args:
name: the name of this object (the value of the 'id' attribute).
timestamp_seconds: a timestamp in seconds.
value: a value of any type.
Returns:
A dictionary containing 'id', 'timestamp', and 'value' key/value pairs.
"""
assert isinstance(name, types.StringTypes)
assert isinstance(timestamp_seconds, float)
return {'id': name,
'timestamp': utilities.seconds_to_timestamp(timestamp_seconds),
'value': value}
示例4: dump
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def dump(self, output_format):
"""Returns the context graph in the specified format."""
assert isinstance(output_format, types.StringTypes)
self._context_resources.sort(key=lambda x: x['id'])
self._context_relations.sort(key=lambda x: (x['source'], x['target']))
if output_format == 'dot':
return self.to_dot_graph()
elif output_format == 'context_graph':
return self.to_context_graph()
elif output_format == 'resources':
return self.to_context_resources()
else:
msg = 'invalid dump() output_format: %s' % output_format
app.logger.error(msg)
raise collector_error.CollectorError(msg)
示例5: count_relations
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def count_relations(self, output, type_name,
source_type=None, target_type=None):
"""Count relations of the specified type (e.g., "contains").
If the source type and/or target type is specified (e.g., "Node", "Pod",
etc.), count only relations that additionally match that constraint.
"""
assert isinstance(output, dict)
assert isinstance(type_name, types.StringTypes)
if not isinstance(output.get('relations'), list):
return 0
n = 0
for r in output.get('relations'):
assert isinstance(r, dict)
if r['type'] != type_name:
continue
if source_type and r['source'].split(':')[0] != source_type:
continue
if target_type and r['target'].split(':')[0] != target_type:
continue
n += 1
return n
示例6: data_to_float
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def data_to_float(self, data):
return convert_floats(data)
for key, value in data.iteritems():
# Sanity checks
if type(value) in types.StringTypes:
continue
if value is None:
data[key] = None
continue
# Convert to float
try:
data[key] = float(value)
except (TypeError, ValueError) as ex:
log.warn(u'Measurement "{key}: {value}" float conversion failed: {ex}', key=key, value=value, ex=ex)
示例7: writexml
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
if self.raw:
val = self.nodeValue
if not isinstance(val, StringTypes):
val = str(self.nodeValue)
else:
v = self.nodeValue
if not isinstance(v, StringTypes):
v = str(v)
if strip:
v = ' '.join(v.split())
val = escape(v)
if isinstance(val, UnicodeType):
val = val.encode('utf8')
stream.write(val)
示例8: parse_lock_id
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def parse_lock_id(data_str):
"""
Parse string generated by lock_id()
"""
node_id, ip, process_id, _uuid = (
data_str.split('-', 3) + ([None] * 4))[:4]
if type(process_id) in types.StringTypes and process_id.isdigit():
process_id = int(process_id)
else:
process_id = None
rst = {
'node_id': node_id,
'ip': ip,
'process_id': process_id,
'uuid': _uuid,
'txid': None
}
if node_id.startswith('txid:'):
rst['txid'] = node_id.split(':', 1)[1]
return rst
示例9: is_ip4
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def is_ip4(ip):
if type(ip) not in types.StringTypes:
return False
ip = ip.split('.')
for s in ip:
if not s.isdigit():
return False
i = int(s)
if i < 0 or i > 255:
return False
return len(ip) == 4
示例10: expect_exact
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):
"""This is similar to expect(), but uses plain string matching instead
of compiled regular expressions in 'pattern_list'. The 'pattern_list'
may be a string; a list or other sequence of strings; or TIMEOUT and
EOF.
This call might be faster than expect() for two reasons: string
searching is faster than RE matching and it is possible to limit the
search to just the end of the input buffer.
This method is also useful when you don't want to have to worry about
escaping regular expression characters that you want to match."""
if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF):
pattern_list = [pattern_list]
return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
示例11: getint
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def getint(v):
import types
# extract digits from a string to form an integer
try:
return int(v)
except ValueError:
pass
if not isinstance(v, types.StringTypes):
return 0
a = "0"
for d in v:
if d in "0123456789":
a += d
return int(a)
#==============================================================================
# define scale factor for displaying page images (20% larger)
#==============================================================================
示例12: approximate_similarity
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def approximate_similarity(self, v1, v2, bits=None):
"""Return approximate cosine similarity of given words or vectors.
Uses random hyperplane-based locality sensitive hashing (LSH)
with given number of bits. If bits is None, estimate number of
bits to use.
LSH is initialized on the first invocation, which may take
long for large numbers of word vectors. For a small number of
invocations, similarity() may be more efficient.
"""
if self._w2h_lsh is None or (bits is not None and bits != self._w2h_lsh.bits):
if not with_gmpy:
logging.warning('gmpy not available, approximate similarity '
'may be slow.')
self._w2h_lsh = self._initialize_lsh(bits, fill=False)
self._w2h_map = {}
logging.info('init word-to-hash map: start')
for w, v in self:
self._w2h_map[w] = self._w2h_lsh.hash(v)
logging.info('init word-to-hash map: done')
hashes = []
for v in (v1, v2):
if isinstance(v, StringTypes):
h = self._w2h_map[v]
else:
h = self._w2h_lsh.hash(v)
hashes.append(h)
return self._w2h_lsh.hash_similarity(hashes[0], hashes[1])
示例13: nearest
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def nearest(self, v, n=10, exclude=None, candidates=None):
"""Return nearest n words and similarities for given word or vector,
excluding given words.
If v is a string, look up the corresponding word vector.
If exclude is None and v is a string, exclude v.
If candidates is not None, only consider (word, vector)
values from iterable candidates.
Return value is a list of (word, similarity) pairs.
"""
if isinstance(v, StringTypes):
v, w = self.word_to_unit_vector(v), v
else:
v, w = v/numpy.linalg.norm(v), None
if exclude is None:
exclude = [] if w is None else set([w])
if not self._normalized:
sim = partial(self._item_similarity, v=v)
else:
sim = partial(self._item_similarity_normalized, v=v)
if candidates is None:
candidates = self.word_to_vector_mapping().iteritems()
nearest = heapq.nlargest(n+len(exclude), candidates, sim)
wordsim = [(p[0], sim(p)) for p in nearest if p[0] not in exclude]
return wordsim[:n]
示例14: format
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def format(self, value):
if isinstance(value, types.StringTypes):
return value
else:
return str(value)
示例15: get_file_watcher
# 需要导入模块: import types [as 别名]
# 或者: from types import StringTypes [as 别名]
def get_file_watcher(directories, use_mtime_file_watcher):
"""Returns an instance that monitors a hierarchy of directories.
Args:
directories: A list representing the paths of the directories to monitor.
use_mtime_file_watcher: A bool containing whether to use mtime polling to
monitor file changes even if other options are available on the current
platform.
Returns:
A FileWatcher appropriate for the current platform. start() must be called
before has_changes().
"""
assert not isinstance(directories, types.StringTypes), 'expected list got str'
if len(directories) != 1:
return _MultipleFileWatcher(directories, use_mtime_file_watcher)
directory = directories[0]
if use_mtime_file_watcher:
return mtime_file_watcher.MtimeFileWatcher(directory)
elif sys.platform.startswith('linux'):
return inotify_file_watcher.InotifyFileWatcher(directory)
elif sys.platform.startswith('win'):
return win32_file_watcher.Win32FileWatcher(directory)
return mtime_file_watcher.MtimeFileWatcher(directory)
# NOTE: The Darwin-specific watcher implementation (found in the deleted file
# fsevents_file_watcher.py) was incorrect - the Mac OS X FSEvents
# implementation does not detect changes in symlinked files or directories. It
# also does not provide file-level change precision before Mac OS 10.7.
#
# It is still possible to provide an efficient implementation by watching all
# symlinked directories and using mtime checking for symlinked files. On any
# change in a directory, it would have to be rescanned to see if a new
# symlinked file or directory was added. It also might be possible to use
# kevents instead of the Carbon API to detect files changes.