本文整理匯總了Python中os.path.commonprefix方法的典型用法代碼示例。如果您正苦於以下問題:Python path.commonprefix方法的具體用法?Python path.commonprefix怎麽用?Python path.commonprefix使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類os.path
的用法示例。
在下文中一共展示了path.commonprefix方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _common_shorten_repr
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def _common_shorten_repr(*args):
args = tuple(map(safe_repr, args))
maxlen = max(map(len, args))
if maxlen <= _MAX_LENGTH:
return args
prefix = commonprefix(args)
prefixlen = len(prefix)
common_len = _MAX_LENGTH - \
(maxlen - prefixlen + _MIN_BEGIN_LEN + _PLACEHOLDER_LEN)
if common_len > _MIN_COMMON_LEN:
assert _MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + \
(maxlen - prefixlen) < _MAX_LENGTH
prefix = _shorten(prefix, _MIN_BEGIN_LEN, common_len)
return tuple(prefix + s[prefixlen:] for s in args)
prefix = _shorten(prefix, _MIN_BEGIN_LEN, _MIN_COMMON_LEN)
return tuple(prefix + _shorten(s[prefixlen:], _MIN_DIFF_LEN, _MIN_END_LEN)
for s in args)
示例2: commonpathprefix
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def commonpathprefix(paths):
"""Return the common path prefix and a tuple of the relative subpaths for the
provided paths. Uses resolve_path to convert to absolute paths and returns
the common absolute path. Some subpaths might be the empty string and joining
these will produce paths ending in '/', use normpath if you don't want this.
Python 2.7 only has path.commonprefix, which returns a common string prefix,
not a common path prefix.
"""
norm_paths = [resolve_path(p) + path.sep for p in paths]
prefix = path.dirname(path.commonprefix(norm_paths))
prefix_len = len(prefix)
if prefix_len > 1:
prefix_len += 1 # not '/' so does not end in '/', strip from subpaths
subpaths = tuple(p[prefix_len:-1] for p in norm_paths)
return prefix, subpaths
示例3: write_snapshot_disk_usage_matrix
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def write_snapshot_disk_usage_matrix(filesystem, suppress_common_prefix=True):
snapshot_names = snapshots_in_creation_order(filesystem, strip_filesystem=True)
if suppress_common_prefix:
suppressed_prefix_len = len(commonprefix(snapshot_names))
else:
suppressed_prefix_len = 0
print_csv([[None]+[name[suppressed_prefix_len:] for name in snapshot_names]]) # Start with Column headers
for end in range(len(snapshot_names)):
this_line = [snapshot_names[end][suppressed_prefix_len:]]
for start in range(len(snapshot_names)):
if start <= end:
start_snap = snapshot_names[start]
end_snap = snapshot_names[end]
space_used = space_between_snapshots(filesystem,
start_snap,
end_snap)
this_line.append(space_used)
else:
this_line.append(None)
## Show line we've just done
print_csv([this_line])
示例4: _common_root
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def _common_root(files):
files = [op.realpath(file) for file in files]
root = op.commonprefix(files)
if not op.exists(root):
root = op.dirname(root)
if root:
assert op.exists(root)
assert op.isdir(root), root
return root
示例5: scrape
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def scrape(file_path):
pdf = PdfFileReader(file(file_path, 'rb'))
content = ''
for i in range(0, pdf.numPages):
# TODO figure out why line breaks don't seem to be rendering
content += pdf.getPage(i).extractText() + '\n'
out_file = '.%s' % path.basename(file_path)
out_path = path.join(path.dirname(file_path), out_file)
if options.repo not in path.commonprefix([out_path, options.repo]):
out_path = path.join(options.repo, options.default_notebook, out_file)
content = content.encode('ascii', 'ignore')
f = open(out_path, 'w')
f.write(content)
f.close()
示例6: _update_superevent_details
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def _update_superevent_details(self, super_event):
events = super_event.sub_events.filter(deleted=False)
if not events.exists():
return
# values that should be updated in super-event
update_dict = {}
# name superevent by common part of the subevent names
names = {}
if not super_event.is_user_edited():
# only save common name if super event has not been named by user
# some sub events may still have user edited names, use them if present
for lang in settings.LANGUAGES:
lang = lang[0]
names[lang] = []
lang = lang.replace('-', '_')
if any([getattr(subevent, 'name_'+lang) for subevent in events]):
names[lang].extend([getattr(subevent, 'name_'+lang) for
subevent in events if getattr(subevent, 'name_'+lang, None)])
super_event_name = {}
for lang in settings.LANGUAGES:
lang = lang[0]
super_event_name[lang] = commonprefix(names[lang]).strip(' -:')
lang = lang.replace('-', '_')
if any([getattr(subevent, 'name_'+lang) for subevent in events]):
update_dict['name_'+lang] = super_event_name[lang]
# always update super_event timeframe depending on sub events
first_event = events.order_by('start_time').first()
update_dict['start_time'] = first_event.start_time
update_dict['has_start_time'] = first_event.has_start_time
last_event = events.order_by('-end_time').first()
update_dict['end_time'] = last_event.end_time
update_dict['has_end_time'] = last_event.has_end_time
if any([value != getattr(super_event, key) for key, value in update_dict.items()]):
# if something changed, update
for key, value in update_dict.items():
setattr(super_event, key, value)
super_event.save()
示例7: postprocess_filenames
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def postprocess_filenames(parsed, download_dir):
from os.path import commonprefix, basename # NOQA
# Create a new filename
parsed['new_fpath'] = [join(download_dir, _fname)
for _fname in parsed['new_fname']]
# Remember the original filename
prefix = commonprefix(parsed['img_url'])
parsed['orig_fname'] = [url_[len(prefix):] for url_ in parsed['img_url']]
# Parse out the extension
parsed['ext'] = [splitext(_fname)[-1] for _fname in parsed['new_fname']]
return parsed
示例8: doctree_read
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def doctree_read(app, doctree):
"""
Reads documentation tree for the application and register sources in the generated documentation.
:param app: application
:param doctree: documentation tree
:return None
"""
env = app.builder.env
if not hasattr(env, "_viewcode_modules"):
env._viewcode_modules = {} # type: ignore
if app.builder.name == "singlehtml":
return
for objnode in doctree.traverse(ExampleHeader):
filepath = objnode.get("filename")
relative_path = path.relpath(
filepath, path.commonprefix([app.config.exampleinclude_sourceroot, filepath])
)
modname = relative_path.replace("/", ".")[:-3]
show_button = register_source(app, env, modname)
onlynode = create_node(env, relative_path, show_button)
objnode.replace_self(onlynode)
# pylint: enable=protected-access
示例9: lcprefix
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def lcprefix(self, strings: List[str]) -> str:
"""Return the longest common prefix of a list of strings.
Longest common prefix (LCPrefix).
Parameters
----------
strings : list of strings
Strings for comparison
Returns
-------
str
The longest common prefix
Examples
--------
>>> pfx = LCPrefix()
>>> pfx.lcprefix(['cat', 'hat'])
''
>>> pfx.lcprefix(['Niall', 'Neil'])
'N'
>>> pfx.lcprefix(['aluminum', 'Catalan'])
''
>>> pfx.lcprefix(['ATCG', 'TAGC'])
''
.. versionadded:: 0.4.0
"""
return cast(str, commonprefix(strings))
示例10: lcsuffix
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def lcsuffix(self, strings: List[str]) -> str:
"""Return the longest common suffix of a list of strings.
Longest common suffix (LCSuffix).
Parameters
----------
strings : list of strings
Strings for comparison
Returns
-------
str
The longest common suffix
Examples
--------
>>> sfx = LCSuffix()
>>> sfx.lcsuffix(['cat', 'hat'])
'at'
>>> sfx.lcsuffix(['Niall', 'Neil'])
'l'
>>> sfx.lcsuffix(['aluminum', 'Catalan'])
''
>>> sfx.lcsuffix(['ATCG', 'TAGC'])
''
.. versionadded:: 0.4.0
"""
strings = [s[::-1] for s in strings]
return cast(str, commonprefix(strings)[::-1])
示例11: _group_by_prefix
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def _group_by_prefix(data, prefixes):
"""
Groups a list of input files by longest common prefix over a given list of prefixes
"""
ret = [[] for _ in prefixes]
for doc in data:
ret[sorted(enumerate(commonprefix([doc[1], pre[1]]) for pre in prefixes),
key=lambda x: len(x[1]))[-1][0]].append(doc)
return ret
示例12: commonprefix
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def commonprefix(path=("StringPin", [])):
'''Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string (''). Note that this may return invalid paths because it works a character at a time'''
return osPath.commonprefix(path)
示例13: purge_cloudfront
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def purge_cloudfront(bucket, paths: List[str]) -> None:
"""
Invalidate any CloudFront distribution paths which match the given list of
file paths originating in the given S3 bucket.
"""
cloudfront = aws.client_with_default_region("cloudfront")
# Find the common prefix of this fileset, if any.
prefix = commonprefix(paths)
# For each CloudFront distribution origin serving from this bucket (with a
# matching or broader prefix), if any, purge the prefix path.
for distribution, origin in distribution_origins_for_bucket(cloudfront, bucket.name, prefix):
purge_prefix(cloudfront, distribution, origin, prefix)
示例14: date_common_prefix
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def date_common_prefix(*dates):
prefix = commonprefix(dates)[:10]
if len(prefix) < 10:
prefix = prefix[:7]
if len(prefix) < 7:
prefix = prefix[:4]
if len(prefix) < 4:
prefix = None
return prefix
示例15: dumpsafe
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import commonprefix [as 別名]
def dumpsafe(paths, repl='<sl>'):
"""
enforces that filenames will not conflict.
Removes common the common prefix, and replaces slashes with <sl>
Ignore:
>>> # xdoctest: +REQUIRES(--pygtrie)
>>> paths = ['foo/{:04d}/{:04d}'.format(i, j) for i in range(2) for j in range(20)]
>>> list(dumpsafe(paths, '-'))
"""
common_pref = commonprefix(paths)
if not isdir(common_pref):
im_pref = dirname(common_pref)
if common_pref[len(im_pref):len(im_pref) + 1] == '/':
im_pref += '/'
elif common_pref[len(im_pref):len(im_pref) + 1] == '\\':
im_pref += '\\'
else:
im_pref = common_pref
start = len(im_pref)
dump_paths = (
p[start:].replace('/', repl).replace('\\', repl) # faster
# relpath(p, im_pref).replace('/', repl).replace('\\', repl)
for p in paths
)
return dump_paths