我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用gettext.ngettext()。
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)
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 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 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 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_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 _initGettext(): charset = initLocale() # Try to load gettext module if config.use_i18n: try: import gettext ok = True except ImportError: ok = False else: ok = False # gettext is not available or not needed: use dummy gettext functions if not ok: return (_dummy_gettext, _dummy_ngettext) # Gettext variables package = hachoir_core.PACKAGE locale_dir = path.join(path.dirname(__file__), "..", "locale") # Initialize gettext module gettext.bindtextdomain(package, locale_dir) gettext.textdomain(package) translate = gettext.gettext ngettext = gettext.ngettext # TODO: translate_unicode lambda function really sucks! # => find native function to do that unicode_gettext = lambda text: \ unicode(translate(text), charset) unicode_ngettext = lambda singular, plural, count: \ unicode(ngettext(singular, plural, count), charset) return (unicode_gettext, unicode_ngettext)
def _on_gwibber_fail(self, api, trans, failed_accounts, error): self._change_status("fail", _("Problems posting to Gwibber")) #list to hold service strings in the format: "Service (@username)" failed_services = [] for account in failed_accounts: failed_services.append("%s (@%s)" % ( account['service'].capitalize(), account['username'])) glade_dialog = SimpleGtkbuilderDialog(self.datadir, domain="software-center") dialog = glade_dialog.dialog_gwibber_error dialog.set_transient_for(self.submit_window) # build the failure string # TRANSLATORS: the part in %s can either be a single entry # like "facebook" or a string like # "factbook and twister" error_str = gettext.ngettext( "There was a problem posting this review to %s.", "There was a problem posting this review to %s.", len(failed_services)) error_str = make_string_from_list(error_str, failed_services) dialog.set_markup(error_str) dialog.format_secondary_text(error) result = dialog.run() dialog.destroy() if result == Gtk.RESPONSE_ACCEPT: self._gwibber_retry_some(api, trans, failed_accounts) else: BaseApp.on_transmit_success(self, api, trans)
def _update_appcount(self): enq = AppEnquire(self.cache, self.db) distro = get_distro() if get_global_filter().supported_only: query = distro.get_supported_query() else: query = xapian.Query('') length = enq.get_estimated_matches_count(query) text = gettext.ngettext("%(amount)s item", "%(amount)s items", length ) % {'amount': length} self.appcount.set_text(text)
def _update_appcount(self, appcount): text = gettext.ngettext("%(amount)s item available", "%(amount)s items available", appcount) % {'amount': appcount} self.appcount.set_text(text) return
def _add_where_is_it_commandline(self, pkgname): cmdfinder = CmdFinder(self.cache) cmds = cmdfinder.find_cmds_from_pkgname(pkgname) if not cmds: return vb = Gtk.VBox() vb.set_spacing(12) self.installed_where_hbox.pack_start(vb, False, False, 0) msg = gettext.ngettext( _('This program is run from a terminal: '), _('These programs are run from a terminal: '), len(cmds)) title = Gtk.Label() title.set_alignment(0, 0) title.set_markup(msg) title.set_line_wrap(True) #~ title.set_size_request(self.get_allocation().width-24, -1) vb.pack_start(title, False, False, 0) cmds_str = ", ".join(cmds) cmd_label = Gtk.Label( label='<span font_desc="monospace bold 9">%s</span>' % cmds_str) cmd_label.set_selectable(True) cmd_label.set_use_markup(True) cmd_label.set_alignment(0, 0.5) cmd_label.set_padding(12, 0) cmd_label.set_line_wrap(True) vb.pack_start(cmd_label, False, False, 0) self.installed_where_hbox.show_all()
def set_nr_reviews(self, nr_reviews): s = gettext.ngettext( "%(nr_ratings)i rating", "%(nr_ratings)i ratings", nr_reviews) % {'nr_ratings': nr_reviews} # FIXME don't use fixed color m = '<span color="#8C8C8C"><small>(%s)</small></span>' self.label.set_markup(m % s)