本文整理汇总了Python中natsort.natsorted方法的典型用法代码示例。如果您正苦于以下问题:Python natsort.natsorted方法的具体用法?Python natsort.natsorted怎么用?Python natsort.natsorted使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类natsort
的用法示例。
在下文中一共展示了natsort.natsorted方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: series_list
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def series_list():
if current_user.check_visibility(constants.SIDEBAR_SERIES):
if current_user.series_view == 'list':
entries = calibre_db.session.query(db.Series, func.count('books_series_link.book').label('count')) \
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(text('books_series_link.series')).order_by(db.Series.sort).all()
charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()
return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
title=_(u"Series"), page="serieslist", data="series")
else:
entries = calibre_db.session.query(db.Books, func.count('books_series_link').label('count')) \
.join(db.books_series_link).join(db.Series).filter(calibre_db.common_filters()) \
.group_by(text('books_series_link.series')).order_by(db.Series.sort).all()
charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()
return render_title_template('grid.html', entries=entries, folder='web.books_list', charlist=charlist,
title=_(u"Series"), page="serieslist", data="series", bodyClass="grid-view")
else:
abort(404)
示例2: folder_pathes
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def folder_pathes(path, is_nat_sort=False):
if not os.path.exists(path):
exp_msg = 'Sorry, folder path does not exist: %s' % (path)
raise Exception(exp_msg)
names = os.walk(path).next()[1]
if is_nat_sort:
names = natsort.natsorted(names)
pathes = ['%s/%s' % (path, n) for n in names]
return pathes
# endregion
# region Normalization
示例3: readFileList
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def readFileList(filename):
"""Returns list of files that match the regular expression
Arguments:
filename (str): file name as regular expression
Returns:
str, list: path of files, file names that match the regular expression
"""
#get path
(fpath, fname) = os.path.split(filename)
fnames = os.listdir(fpath);
#fnames = [os.path.join(fpath, x) for x in fnames];
searchRegex = re.compile(fname).search
fl = [ l for l in fnames for m in (searchRegex(l),) if m]
if fl == []:
raise RuntimeError('no files found in ' + fpath + ' match ' + fname + ' !');
#fl.sort();
return fpath, natsort.natsorted(fl);
示例4: transform_project_v2
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def transform_project_v2(project: Project, all_data: bool) -> Dict:
day_downloads = defaultdict(lambda: defaultdict(int))
if all_data:
last_downloads = project.last_downloads()
else:
month_ago = datetime.now().date() - timedelta(days=30)
last_downloads = project.last_downloads(month_ago)
for d in last_downloads:
day_downloads[d.date.isoformat()][d.version] = d.downloads.value
return {
"id": project.name.name,
"total_downloads": project.total_downloads.value,
"versions": natsorted(list(project.versions())),
"downloads": day_downloads,
}
示例5: __init__
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def __init__(self, config={}):
# Hyperparameters
self.update_batch_size = FLAGS.update_batch_size
self.test_batch_size = FLAGS.train_update_batch_size if FLAGS.train_update_batch_size != -1 else self.update_batch_size
self.meta_batch_size = FLAGS.meta_batch_size
self.T = FLAGS.T
self.demo_gif_dir = FLAGS.demo_gif_dir
self.gif_prefix = FLAGS.gif_prefix
self.restore_iter = FLAGS.restore_iter
# Scale and bias for data normalization
self.scale, self.bias = None, None
demo_file = FLAGS.demo_file
demo_file = natsorted(glob.glob(demo_file + '/*pkl'))
self.dataset_size = len(demo_file)
if FLAGS.train and FLAGS.training_set_size != -1:
tmp = demo_file[:FLAGS.training_set_size]
tmp.extend(demo_file[-FLAGS.val_set_size:])
demo_file = tmp
self.extract_supervised_data(demo_file)
if FLAGS.use_noisy_demos:
self.noisy_demo_gif_dir = FLAGS.noisy_demo_gif_dir
noisy_demo_file = FLAGS.noisy_demo_file
self.extract_supervised_data(noisy_demo_file, noisy=True)
示例6: showAll
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def showAll(dir):
Table = []
TableHeader = ['Species', 'Augustus', 'GeneMark',
'Snap', 'GlimmerHMM', 'CodingQuarry', 'Date']
for f in os.listdir(dir):
ff = os.path.join(dir, f)
if os.path.isdir(ff) and lib.checkannotations(os.path.join(ff, 'info.json')):
with open(os.path.join(ff, 'info.json')) as infile:
data = json.load(infile)
sources = [f]
for x in ['augustus', 'genemark', 'snap', 'glimmerhmm', 'codingquarry']:
if x in data:
if len(data[x][0]) < 1:
sources.append('None')
else:
sourceFile = data[x][0]['source']
if ': ' in sourceFile:
sourceFile = sourceFile.split(':')[0]
sources.append(sourceFile)
sources.append(data['augustus'][0]['date'])
Table.append(sources)
Table = natsorted(Table, key=lambda x: x[0])
Table.insert(0, TableHeader)
lib.print_table(Table, max_col_width=40)
示例7: request_files
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def request_files(dataset_dir,
protocol='speaker_independent',
speaker_id=None,
view_id='1',
utterance_types='dst',
content='video'):
if protocol == 'single_speaker':
train, test = _preload_files_single_volunteer(dataset_dir, speaker_id, view_id, utterance_types)
elif protocol == 'speaker_independent':
train, test = _preload_files_speaker_independent(dataset_dir, view_id, utterance_types)
if content == 'audio':
import re
train = [re.sub('_v\d_', '_', file) for file in train]
train = [re.sub('.mp4', '.wav', file) for file in train]
test = [re.sub('_v\d_', '_', file) for file in test]
test = [re.sub('.mp4', '.wav', file) for file in test]
else:
raise Exception('undefined dataset split protocol')
return natsorted(train), natsorted(test)
示例8: find_file_names
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def find_file_names(path, type=".png"):
"""
Finds all files with the given extension in the folder path.
Parameters
----------
path : str
The path to the folder containing the files of interest
type : str
The file postfix such as ".png", ".bmp" etc.
Returns
-------
List of filenames
"""
return natsorted([os.path.join(path, file) for file in os.listdir(path) if file.endswith(type)])
示例9: read_dicom_series
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def read_dicom_series(directory, filepattern="P_*"):
""" Reads a DICOM Series files in the given directory.
Only filesnames matching filepattern will be considered"""
if not os.path.exists(directory) or not os.path.isdir(directory):
raise ValueError("Given directory does not exist or is a file : " + str(directory))
# print('\tRead Dicom', directory)
lstFilesDCM = natsort.natsorted(glob.glob(os.path.join(directory, filepattern)))
# print('\tLength dicom series', len(lstFilesDCM))
# Get ref file
RefDs = dicom.read_file(lstFilesDCM[0])
# Load dimensions based on the number of rows, columns, and slices (along the Z axis)
ConstPixelDims = (int(RefDs.Rows), int(RefDs.Columns), len(lstFilesDCM))
# The array is sized based on 'ConstPixelDims'
ArrayDicom = np.zeros(ConstPixelDims, dtype=RefDs.pixel_array.dtype)
# loop through all the DICOM files
for filenameDCM in lstFilesDCM:
# read the file
ds = dicom.read_file(filenameDCM)
# store the raw image data
ArrayDicom[:, :, lstFilesDCM.index(filenameDCM)] = ds.pixel_array
return ArrayDicom
示例10: __init__
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def __init__(self, opt):
"""Initialize this dataset class.
Parameters:
opt (option dicts) -- stores all the experiment options;
"""
self.opt = opt
self.K = opt['K']
self.fonteffects_dir = opt['fonteffects_dir']
self.num_cls = opt['num_cls']
self.clsdict = {}
for i,source_cls in enumerate(source_cls for source_cls in natsorted(os.listdir(self.fonteffects_dir)) if not source_cls.startswith('.')):
self.clsdict[str(source_cls)] = i
if i >= self.num_cls-1:
break
self.transform_fonteffects = get_transform(self.opt)
示例11: parse_docfiles
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def parse_docfiles(docfiles_dir, link_root):
"""
Create the list of the projects.
The list of projects is computed by walking the `docfiles_dir` and
searching for project paths (<project-name>/<version>/index.html)
"""
if not os.path.exists(docfiles_dir):
return {}
projects = list()
for folder in natsort.natsorted(os.listdir(docfiles_dir), key=str.lower):
if not os.path.isdir(os.path.join(docfiles_dir, folder)):
continue
project = _get_proj_dict(docfiles_dir, folder, link_root)
if project is not None:
projects.append(project)
return projects
示例12: parse_lflist
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def parse_lflist(filename):
lst = {}
with open(filename, 'r', encoding='utf-8') as fp:
for line in fp:
line = line.rstrip('\n')
if not line or line.startswith('#'):
continue
elif line.startswith('!'):
section = line[1:].lower()
lst[section] = Banlist(section)
else:
code, num_allowed, *extra = line.split(' ', 2)
code = int(code)
num_allowed = int(num_allowed)
lst[section].add(code, num_allowed)
return collections.OrderedDict(natsort.natsorted(lst.items(), reverse=True))
示例13: __list_cards
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def __list_cards(self, cards, pl, currently_allowed = None, previously_allowed = None):
# getting all data
data = pl.cdb.execute('SELECT id, name FROM texts WHERE id IN ({0})'.format(', '.join([str(c) for c in cards]))).fetchall()
if len(data) < len(cards):
# not all cards are available in the player's language
# fill up with english ones
already_present = set([d[0] for d in data])
remaining = cards - already_present
data_r = globals.language_handler.primary_database.execute('SELECT id, name FROM texts WHERE id IN ({0})'.format(', '.join([str(c) for c in remaining]))).fetchall()
data = data + data_r
for d in natsort.natsorted(data, key = lambda d: d[1]):
if currently_allowed and previously_allowed:
pl.notify("\t" + pl._("{0} (now at {1}, previously at {2})").format(d[1], currently_allowed[d[0]], previously_allowed[d[0]]))
elif previously_allowed:
pl.notify("\t" + pl._("{0}, (previously at {1})").format(d[1], previously_allowed[d[0]]))
else:
pl.notify("\t" + d[1])
示例14: show_usable
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def show_usable(self, pl):
summonable = natsort.natsorted([card.get_spec(pl) for card in self.summonable])
spsummon = natsort.natsorted([card.get_spec(pl) for card in self.spsummon])
repos = natsort.natsorted([card.get_spec(pl) for card in self.repos])
mset = natsort.natsorted([card.get_spec(pl) for card in self.idle_mset])
idle_set = natsort.natsorted([card.get_spec(pl) for card in self.idle_set])
idle_activate = natsort.natsorted([card.get_spec(pl) for card in self.idle_activate])
if summonable:
pl.notify(pl._("Summonable in attack position: %s") % ", ".join(summonable))
if mset:
pl.notify(pl._("Summonable in defense position: %s") % ", ".join(mset))
if spsummon:
pl.notify(pl._("Special summonable: %s") % ", ".join(spsummon))
if idle_activate:
pl.notify(pl._("Activatable: %s") % ", ".join(idle_activate))
if repos:
pl.notify(pl._("Repositionable: %s") % ", ".join(repos))
if idle_set:
pl.notify(pl._("Settable: %s") % ", ".join(idle_set))
示例15: get_a_problem_file_list
# 需要导入模块: import natsort [as 别名]
# 或者: from natsort import natsorted [as 别名]
def get_a_problem_file_list(problem_paths):
files_to_solve = []
for problem_path in problem_paths:
if path.isdir(problem_path):
for in_fn in natsorted(glob(path.join(problem_path, "*.vrp"))):
files_to_solve.append( in_fn )
for in_fn in natsorted(glob(path.join(problem_path, "*.tsp"))):
files_to_solve.append( in_fn )
for in_fn in natsorted(glob(path.join(problem_path, "*.pickle"))):
files_to_solve.append( in_fn )
elif path.isfile(problem_path) and problem_path[-4:].lower()==".txt":
with open(problem_path, 'r') as vrp_list_file:
for line in vrp_list_file.readlines():
line = line.strip()
if path.isfile(line):
files_to_solve.append(line)
elif path.isfile(problem_path) and (problem_path[-4:].lower()==".vrp" or
problem_path[-4:].lower()==".tsp" or
problem_path[-7:].lower()==".pickle"):
files_to_solve.append( problem_path )
else:
print(problem_path, "is not a .vrp file, folder, or text file",
file=sys.stderr)
return files_to_solve