def monthly(rrule):
"""
Convert a rule with a monthly frequency to text
"""
text = []
byweekday = rrule._original_rule.get('byweekday', [])
bymonthday = rrule._original_rule.get('bymonthday', [])
if rrule._original_rule.get('bymonth', []):
if rrule._interval != 1:
text.extend([' ', str(rrule._interval), ' ', _('months'), ' ', _('in')])
text.append(_bymonth(rrule))
else:
if rrule._interval != 1:
text.extend([' ', str(rrule._interval), ])
text.extend([' ', gettext.ngettext('month', 'months', rrule._interval)])
if bymonthday:
text.append(_bymonthday(rrule))
elif byweekday and _is_weekdays(byweekday):
text.extend([' ', _('on'), ' ', _('weekdays')])
elif byweekday:
text.append(_byweekday(rrule))
return ''.join(text)
python类ngettext()的实例源码
def rrule_to_text(rrule):
"""
Based on https://github.com/jkbrzt/rrule/
Convert an rrule data structure to human-readable text
"""
text = ['every', ]
if not hasattr(rrule, '_freq'):
raise Exception("Missing _freq")
if rrule._freq + 1 > len(FREQUENCY):
raise Exception("Can't do that frequency.")
text.append(FREQUENCY[rrule._freq](rrule))
if rrule._until:
text.extend([' ', _('until'), ' ', rrule._until.strftime(DATE_FORMAT)])
elif rrule._count:
text.extend([' ', _('for'), ' ', str(rrule._count), ])
text.extend([' ', gettext.ngettext('time', 'times', rrule._count)])
return ''.join(text)
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = ngettext('expected %s argument',
'expected %s arguments',
action.nargs) % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def filesizeformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
"""
try:
bytes = float(bytes)
except TypeError:
return "0 bytes"
if bytes < 1024:
return ngettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
if bytes < 1024 * 1024:
return _("%.1f KB") % (bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return _("%.1f MB") % (bytes / (1024 * 1024))
return _("%.1f GB") % (bytes / (1024 * 1024 * 1024))
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = ngettext('expected %s argument',
'expected %s arguments',
action.nargs) % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = ngettext('expected %s argument',
'expected %s arguments',
action.nargs) % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = ngettext('expected %s argument',
'expected %s arguments',
action.nargs) % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def make_string_from_list(base_str, item_list):
""" This function takes a list of items and builds a nice human readable
string with it of the form. Note that the base string needs a "%s".
Example return:
The base string with the list items a,b and c in it.
Note that base_str needs to be a ngettext string already, so the
example usage is:
l = ["foo", "bar"]
base_str = ngettext("This list: %s.", "This list: %s", len(l))
s = make_string_from_list(base_string, l)
"""
list_str = item_list[0]
if len(item_list) > 1:
# TRANSLATORS: this is a generic list delimit char, e.g. "foo, bar"
list_str = _(", ").join(item_list[:-1])
# TRANSLATORS: this is the last part of a list, e.g. "foo, bar and baz"
list_str = _("%s and %s") % (list_str,
item_list[-1])
s = base_str % list_str
return s
def get_include_parent_suggestion_text(self, term, category, state):
if not state.subcategory:
return
enq = self.enquirer
query = self.db.get_query_list_from_search_entry(
term,
category.query)
enq.set_query(query,
limit=state.limit,
sortmode=self.pane.get_sort_mode(),
nonapps_visible=self.pane.nonapps_visible,
filter=state.filter,
nonblocking_load=False)
if enq.nr_apps > 0:
text = self.BULLET % gettext.ngettext("Try "
"<a href=\"search-parent/\">the item "
"in %(category)s</a> that matches", "Try "
"<a href=\"search-parent/\">the %(n)d items "
"in %(category)s</a> that match",
n=enq.nr_apps) % \
{'category': category.name, 'n': enq.nr_apps}
return text
def make_string_from_list(base_str, item_list):
""" This function takes a list of items and builds a nice human readable
string with it of the form. Note that the base string needs a "%s".
Example return:
The base string with the list items a,b and c in it.
Note that base_str needs to be a ngettext string already, so the
example usage is:
l = ["foo", "bar"]
base_str = ngettext("This list: %s.", "This list: %s", len(l))
s = make_string_from_list(base_string, l)
"""
list_str = item_list[0]
if len(item_list) > 1:
# TRANSLATORS: this is a generic list delimit char, e.g. "foo, bar"
list_str = _(", ").join(item_list[:-1])
# TRANSLATORS: this is the last part of a list, e.g. "foo, bar and baz"
list_str = _("%s and %s") % (list_str,
item_list[-1])
s = base_str % list_str
return s
def action_verify(self, ids):
try:
new_ids = [int(i) for i in ids]
# .update() sucks
emotes = Emote.query.filter(Emote.id.in_(new_ids)).all()
for emote in emotes:
emote.verified = True
db.session.commit()
flash(ngettext('Emote successfully verified.',
'%s emotes were successfully verified.' % len(emotes),
emotes))
except Exception as e:
if not self.handle_view_exception(e):
raise
flash('Failed to verify emotes. %s' % str(e), 'error')
def _match_argument(self, action, arg_strings_pattern):
# match the pattern for this action to the arg strings
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
# raise an exception if we weren't able to find a match
if match is None:
nargs_errors = {
None: _('expected one argument'),
OPTIONAL: _('expected at most one argument'),
ONE_OR_MORE: _('expected at least one argument'),
}
default = ngettext('expected %s argument',
'expected %s arguments',
action.nargs) % action.nargs
msg = nargs_errors.get(action.nargs, default)
raise ArgumentError(action, msg)
# return the number of arguments matched
return len(match.group(1))
def hourly(rrule):
"""
Convert a rule with an hourly frequency to text
"""
text = []
if rrule._interval != 1:
text.extend([' ', str(rrule._interval)])
text.extend([' ', gettext.ngettext('hour', 'hours', rrule._interval)])
return ''.join(text)
def daily(rrule):
"""
Convert a rule with a daily frequency to text
"""
text = []
byweekday = rrule._original_rule.get('byweekday', [])
bymonthday = rrule._original_rule.get('bymonthday', [])
if rrule._interval != 1:
text.extend([' ', str(rrule._interval)])
if byweekday and _is_weekdays(byweekday):
text.extend([' ', gettext.ngettext('weekday', 'weekdays', rrule._interval)])
else:
text.extend([' ', gettext.ngettext('day', 'days', rrule._interval)])
if rrule._original_rule.get('bymonth', []):
text.extend([' ', _('in'), _bymonth(rrule)])
if bymonthday:
text.append(_bymonthday(rrule))
elif byweekday:
text.append(_byweekday(rrule))
elif rrule._original_rule.get('byhour', []):
text.append(_byhour(rrule))
return ''.join(text)
def daily_struct(rrule):
"""
Convert a rule with a daily frequency to a structure
"""
schedule = dict(hours='', days='', date_range='', extras='', exceptions='',
frequency='daily', place=None, more_info_url='', start_date=None, end_date=None,
schedule_type='')
byweekday = rrule._original_rule.get('byweekday', [])
bymonthday = rrule._original_rule.get('bymonthday', [])
bymonth = rrule._original_rule.get('bymonth', [])
byhour = rrule._original_rule.get('byhour', [])
if rrule._interval != 1:
if byweekday and _is_weekdays(byweekday):
schedule['days'] = ' '.join([str(rrule._interval), gettext.ngettext('weekday', 'weekdays', rrule._interval)])
else:
schedule['days'] = ' '.join([str(rrule._interval), gettext.ngettext('day', 'days', rrule._interval)])
else:
schedule['days'] = ''
if bymonth:
if schedule['days']:
schedule['days'] = " ".join(schedule['days'], _('in'), _bymonth(rrule))
else:
schedule['days'] = _bymonth(rrule)
if bymonthday:
schedule['days'] = "%s%s" % (schedule['days'], _bymonthday(rrule))
elif byweekday:
schedule['days'] = "%s%s" % (schedule['days'], _byweekday_struct(rrule))
elif byhour:
schedule['hours'] = _list(map(format_time, byhour))
return Schedule(**schedule)
def weekly(rrule):
"""
Convert a rule with a weekly frequency to text
"""
text = []
byweekday = rrule._original_rule.get('byweekday', [])
bymonthday = rrule._original_rule.get('bymonthday', [])
if rrule._interval != 1:
text.extend([' ', str(rrule._interval), ' ', gettext.ngettext('week', 'weeks', rrule._interval)])
if byweekday and _is_weekdays(byweekday):
if rrule._interval == 1:
text.extend([' ', gettext.ngettext('weekday', 'weekdays', rrule._interval)])
else:
text.extend([' ', _('on'), _('weekdays')])
else:
if rrule._interval == 1:
text.extend([' ', _('week')])
if rrule._original_rule.get('bymonth', []):
text.extend([' ', _('in'), _bymonth(rrule)])
if bymonthday:
text.append(_bymonthday(rrule))
elif byweekday:
text.append(_byweekday(rrule))
return ''.join(text)
def rrule_to_schedule(rrule, dtstart=None):
"""
Convert an rrule data structure to schedule
"""
if not hasattr(rrule, '_freq'):
raise Exception("Missing _freq")
if rrule._freq + 1 > len(FREQUENCY_STRUCT):
raise Exception("Can't do that frequency.")
schedule = FREQUENCY_STRUCT[rrule._freq](rrule)
past = rrule._until and tz.now().date() > rrule._until.date()
upcoming = dtstart is not None and tz.now().date() < dtstart
current = not upcoming and not past
schedule_type = ''
if past:
schedule_type = 'past'
elif upcoming:
schedule_type = 'upcoming'
elif current:
schedule_type = 'current'
schedule = schedule._replace(schedule_type=schedule_type)
if rrule._until:
if dtstart is not None:
schedule = schedule._replace(date_range=" - ".join([datetime.datetime.strftime(dtstart, DATE_FORMAT), rrule._until.strftime(DATE_FORMAT)]))
else:
schedule = schedule._replace(date_range=" ".join([_('until'), rrule._until.strftime(DATE_FORMAT)]))
schedule = schedule._replace(end_date=rrule._until.date())
# elif rrule._count:
# text.extend([' ', _('for'), ' ', str(rrule._count), ])
# text.extend([' ', gettext.ngettext('time', 'times', rrule._count)])
return schedule
def _handle_conflict_error(self, action, conflicting_actions):
message = ngettext('conflicting option string: %s',
'conflicting option strings: %s',
len(conflicting_actions))
conflict_string = ', '.join([option_string
for option_string, action
in conflicting_actions])
raise ArgumentError(action, message % conflict_string)
def test_plural_forms1(self):
eq = self.assertEqual
x = gettext.ngettext('There is %s file', 'There are %s files', 1)
eq(x, 'Hay %s fichero')
x = gettext.ngettext('There is %s file', 'There are %s files', 2)
eq(x, 'Hay %s ficheros')
def test_plural_forms2(self):
eq = self.assertEqual
with open(self.mofile, 'rb') as fp:
t = gettext.GNUTranslations(fp)
x = t.ngettext('There is %s file', 'There are %s files', 1)
eq(x, 'Hay %s fichero')
x = t.ngettext('There is %s file', 'There are %s files', 2)
eq(x, 'Hay %s ficheros')
def _n(singular, plural, n):
return utf8(gettext.ngettext(singular, plural, n))
def test_plural_forms1(self):
eq = self.assertEqual
x = gettext.ngettext('There is %s file', 'There are %s files', 1)
eq(x, 'Hay %s fichero')
x = gettext.ngettext('There is %s file', 'There are %s files', 2)
eq(x, 'Hay %s ficheros')
def test_plural_forms2(self):
eq = self.assertEqual
with open(self.mofile, 'rb') as fp:
t = gettext.GNUTranslations(fp)
x = t.ngettext('There is %s file', 'There are %s files', 1)
eq(x, 'Hay %s fichero')
x = t.ngettext('There is %s file', 'There are %s files', 2)
eq(x, 'Hay %s ficheros')
# Examples from http://www.gnu.org/software/gettext/manual/gettext.html
def test_plural_forms1(self):
eq = self.assertEqual
x = gettext.ngettext('There is %s file', 'There are %s files', 1)
eq(x, 'Hay %s fichero')
x = gettext.ngettext('There is %s file', 'There are %s files', 2)
eq(x, 'Hay %s ficheros')
def test_plural_forms2(self):
eq = self.assertEqual
with open(self.mofile, 'rb') as fp:
t = gettext.GNUTranslations(fp)
x = t.ngettext('There is %s file', 'There are %s files', 1)
eq(x, 'Hay %s fichero')
x = t.ngettext('There is %s file', 'There are %s files', 2)
eq(x, 'Hay %s ficheros')
# Examples from http://www.gnu.org/software/gettext/manual/gettext.html
def ngettext(singular, plural, n):
if n == 1:
return singular
return plural
def _process_long_opt(self, rargs, values):
arg = rargs.pop(0)
# Value explicitly attached to arg? Pretend it's the next
# argument.
if "=" in arg:
(opt, next_arg) = arg.split("=", 1)
rargs.insert(0, next_arg)
had_explicit_value = True
else:
opt = arg
had_explicit_value = False
opt = self._match_long_opt(opt)
option = self._long_opt[opt]
if option.takes_value():
nargs = option.nargs
if len(rargs) < nargs:
self.error(ngettext(
"%(option)s option requires %(number)d argument",
"%(option)s option requires %(number)d arguments",
nargs) % {"option": opt, "number": nargs})
elif nargs == 1:
value = rargs.pop(0)
else:
value = tuple(rargs[0:nargs])
del rargs[0:nargs]
elif had_explicit_value:
self.error(_("%s option does not take a value") % opt)
else:
value = None
option.process(opt, value, values, self)
def _process_short_opts(self, rargs, values):
arg = rargs.pop(0)
stop = False
i = 1
for ch in arg[1:]:
opt = "-" + ch
option = self._short_opt.get(opt)
i += 1 # we have consumed a character
if not option:
raise BadOptionError(opt)
if option.takes_value():
# Any characters left in arg? Pretend they're the
# next arg, and stop consuming characters of arg.
if i < len(arg):
rargs.insert(0, arg[i:])
stop = True
nargs = option.nargs
if len(rargs) < nargs:
self.error(ngettext(
"%(option)s option requires %(number)d argument",
"%(option)s option requires %(number)d arguments",
nargs) % {"option": opt, "number": nargs})
elif nargs == 1:
value = rargs.pop(0)
else:
value = tuple(rargs[0:nargs])
del rargs[0:nargs]
else: # option doesn't take a value
value = None
option.process(opt, value, values, self)
if stop:
break
# -- Feedback methods ----------------------------------------------
def _handle_conflict_error(self, action, conflicting_actions):
message = ngettext('conflicting option string: %s',
'conflicting option strings: %s',
len(conflicting_actions))
conflict_string = ', '.join([option_string
for option_string, action
in conflicting_actions])
raise ArgumentError(action, message % conflict_string)
def test_plural_forms2(self):
eq = self.assertEqual
with open(self.mofile, 'rb') as fp:
t = gettext.GNUTranslations(fp)
x = t.ngettext('There is %s file', 'There are %s files', 1)
eq(x, 'Hay %s fichero')
x = t.ngettext('There is %s file', 'There are %s files', 2)
eq(x, 'Hay %s ficheros')