当前位置: 首页>>代码示例>>Python>>正文


Python compat.unicode函数代码示例

本文整理汇总了Python中weboob.tools.compat.unicode函数的典型用法代码示例。如果您正苦于以下问题:Python unicode函数的具体用法?Python unicode怎么用?Python unicode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了unicode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: bcall_errors_handler

    def bcall_errors_handler(self, errors):
        """
        Handler for the CallErrors exception.
        """
        self.ind.set_status(appindicator.IndicatorStatus.ATTENTION)
        for backend, error, backtrace in errors.errors:
            notify = True
            if isinstance(error, BrowserIncorrectPassword):
                msg = 'invalid login/password.'
            elif isinstance(error, BrowserSSLError):
                msg = '/!\ SERVER CERTIFICATE IS INVALID /!\\'
            elif isinstance(error, BrowserForbidden):
                msg = unicode(error) or 'Forbidden'
            elif isinstance(error, BrowserUnavailable):
                msg = unicode(error)
                if not msg:
                    msg = 'website is unavailable.'
            elif isinstance(error, NotImplementedError):
                notify = False
            elif isinstance(error, UserError):
                msg = unicode(error)
            elif isinstance(error, MoreResultsAvailable):
                notify = False
            else:
                msg = unicode(error)

            if notify:
                Notify.Notification.new('<b>Error Boobank: %s</b>' % backend.name,
                                        msg,
                                        'notification-message-im').show()
开发者ID:laurentb,项目名称:weboob,代码行数:30,代码来源:boobank_indicator.py

示例2: __init__

    def __init__(self, video, parent=None):
        super(Video, self).__init__(parent)
        self.ui = Ui_Video()
        self.ui.setupUi(self)

        self.video = video
        self.setWindowTitle("Video - %s" % video.title)
        self.ui.urlEdit.setText(video.url)
        self.ui.titleLabel.setText(video.title)
        self.ui.durationLabel.setText(unicode(video.duration))
        self.ui.authorLabel.setText(unicode(video.author))
        self.ui.dateLabel.setText(unicode(video.date))
        if video.rating_max:
            self.ui.ratingLabel.setText('%s / %s' % (video.rating, video.rating_max))
        else:
            self.ui.ratingLabel.setText('%s' % video.rating)

        self.mediaPlayer = QMediaPlayer()

        self.mediaPlayer.durationChanged.connect(self._setMax)
        self.mediaPlayer.seekableChanged.connect(self.ui.seekSlider.setEnabled)
        self.mediaPlayer.positionChanged.connect(self._slide)
        self.ui.seekSlider.valueChanged.connect(self.mediaPlayer.setPosition)

        mc = QMediaContent(QUrl(video.url))
        self.mediaPlayer.setMedia(mc)
        self.ui.videoPlayer.setMediaObject(self.mediaPlayer)
        self.mediaPlayer.play()
开发者ID:P4ncake,项目名称:weboob,代码行数:28,代码来源:video.py

示例3: create_transfer

 def create_transfer(self, account, recipient, transfer):
     transfer = Transfer()
     transfer.currency = FrenchTransaction.Currency('.//tr[td[contains(text(), "Montant")]]/td[not(@class)] | \
                                                     .//tr[th[contains(text(), "Montant")]]/td[not(@class)]')(self.doc)
     transfer.amount = CleanDecimal('.//tr[td[contains(text(), "Montant")]]/td[not(@class)] | \
                                     .//tr[th[contains(text(), "Montant")]]/td[not(@class)]', replace_dots=True)(self.doc)
     transfer.account_iban = account.iban
     if recipient.category == u'Externe':
         for word in Upper(CleanText(u'.//tr[th[contains(text(), "Compte à créditer")]]/td[not(@class)]'))(self.doc).split():
             if is_iban_valid(word):
                 transfer.recipient_iban = word
                 break
         else:
             raise TransferError('Unable to find IBAN (original was %s)' % recipient.iban)
     else:
         transfer.recipient_iban = recipient.iban
     transfer.account_id = unicode(account.id)
     transfer.recipient_id = unicode(recipient.id)
     transfer.exec_date = Date(CleanText('.//tr[th[contains(text(), "En date du")]]/td[not(@class)]'), dayfirst=True)(self.doc)
     transfer.label = (CleanText(u'.//tr[td[contains(text(), "Motif de l\'opération")]]/td[not(@class)]')(self.doc) or
                      CleanText(u'.//tr[td[contains(text(), "Libellé")]]/td[not(@class)]')(self.doc) or
                      CleanText(u'.//tr[th[contains(text(), "Libellé")]]/td[not(@class)]')(self.doc))
     transfer.account_label = account.label
     transfer.recipient_label = recipient.label
     transfer._account = account
     transfer._recipient = recipient
     transfer.account_balance = account.balance
     return transfer
开发者ID:P4ncake,项目名称:weboob,代码行数:28,代码来源:pages.py

示例4: unique_id

    def unique_id(self, seen=None, account_id=None):
        """
        Get an unique ID for the transaction based on date, amount and raw.

        :param seen: if given, the method uses this dictionary as a cache to
                     prevent several transactions with the same values to have the same
                     unique ID.
        :type seen: :class:`dict`
        :param account_id: if given, add the account ID in data used to create
                           the unique ID. Can be useful if you want your ID to be unique across
                           several accounts.
        :type account_id: :class:`str`
        :returns: an unique ID encoded in 8 length hexadecimal string (for example ``'a64e1bc9'``)
        :rtype: :class:`str`
        """
        crc = crc32(unicode(self.date).encode('utf-8'))
        crc = crc32(unicode(self.amount).encode('utf-8'), crc)
        if not empty(self.raw):
            label = self.raw
        else:
            label = self.label

        crc = crc32(re.sub('[ ]+', ' ', label).encode("utf-8"), crc)

        if account_id is not None:
            crc = crc32(unicode(account_id).encode('utf-8'), crc)

        if seen is not None:
            while crc in seen:
                crc = crc32(b"*", crc)

            seen.add(crc)

        return "%08x" % (crc & 0xffffffff)
开发者ID:laurentb,项目名称:weboob,代码行数:34,代码来源:bank.py

示例5: parse

    def parse(self):
        self.url = '%s#%s' % (self.preurl, self.div.attrib['id'])
        self.title = unicode(self.div.find('h2').xpath('.//a[has-class("title")]')[0].text)
        try:
            a = self.div.find('p').xpath('.//a[@rel="author"]')[0]
        except IndexError:
            self.author = 'Anonyme'
            self.username = None
        else:
            self.author = unicode(a.text)
            self.username = unicode(a.attrib['href'].split('/')[2])
        self.date = datetime.strptime(self.div.find('p').xpath('.//time')[0].attrib['datetime'].split('+')[0],
                                      '%Y-%m-%dT%H:%M:%S')
        self.date = local2utc(self.date)

        content = self.div.find('div')
        try:
            signature = content.xpath('.//p[has-class("signature")]')[0]
        except IndexError:
            # No signature.
            pass
        else:
            content.remove(signature)
            self.signature = lxml.html.tostring(signature).decode('utf-8')
        self.body = lxml.html.tostring(content).decode('utf-8')

        self.score = int(self.div.find('p').xpath('.//span[has-class("score")]')[0].text)
        forms = self.div.find('footer').xpath('.//form[has-class("button_to")]')
        if len(forms) > 0:
            self.relevance_url = forms[0].attrib['action'].rstrip('for').rstrip('against')
            self.relevance_token = forms[0].xpath('.//input[@name="authenticity_token"]')[0].attrib['value']
开发者ID:P4ncake,项目名称:weboob,代码行数:31,代码来源:news.py

示例6: __init__

    def __init__(self, browser, url, tree):
        super(Article, self).__init__(browser)
        self.url = url
        self.id = url2id(self.url)

        if tree is None:
            return

        header = tree.find('header')
        self.title = u' — '.join([a.text for a in header.find('h1').xpath('.//a')])
        try:
            a = header.xpath('.//a[@rel="author"]')[0]
        except IndexError:
            self.author = 'Anonyme'
            self.username = None
        else:
            self.author = unicode(a.text)
            self.username = unicode(a.attrib['href'].split('/')[2])
        self.body = lxml.html.tostring(tree.xpath('.//div[has-class("content")]')[0]).decode('utf-8')
        try:
            self.date = datetime.strptime(header.xpath('.//time')[0].attrib['datetime'].split('+')[0],
                                          '%Y-%m-%dT%H:%M:%S')
            self.date = local2utc(self.date)
        except IndexError:
            pass
        for form in tree.find('footer').xpath('//form[has-class("button_to")]'):
            if form.attrib['action'].endswith('/for'):
                self.relevance_url = form.attrib['action'].rstrip('for').rstrip('against')
                self.relevance_token = form.xpath('.//input[@name="authenticity_token"]')[0].attrib['value']

        self.score = int(tree.xpath('.//div[has-class("figures")]//figure[has-class("score")]')[0].text)
开发者ID:P4ncake,项目名称:weboob,代码行数:31,代码来源:news.py

示例7: get_arte_cinema_categories

    def get_arte_cinema_categories(self, cat=[]):
        menu = self.videos_list.go(site=SITE.CINEMA.get('id'), lang=self.lang.get('site'),
                                   cat='').get_arte_cinema_menu()
        menuSplit = map(lambda x: x.split("/")[2:], menu)

        result = {}
        for record in menuSplit:
            here = result
            for item in record[:-1]:
                if item not in here:
                    here[item] = {}
                here = here[item]
            if "end" not in here:
                here["end"] = []
            here["end"].append(record[-1])

        cat = cat if not cat else cat[1:]

        if not cat and "end" in result:
            del result["end"]

        for el in cat:
            result = result.get(el)

        if "end" in result.keys():
            return self.page.iter_arte_cinema_categories(cat='/'.join(cat))
        else:
            categories = []
            for item in result.keys():
                if item == "programs":
                    continue
                categories.append(Collection([SITE.CINEMA.get('id'), unicode(item)], unicode(item)))
            return categories
开发者ID:P4ncake,项目名称:weboob,代码行数:33,代码来源:browser.py

示例8: filter

 def filter(self, el):
     try:
         el = el[0]
     except IndexError:
         return self.default_or_raise(XPathNotFound('Unable to find element %s' % self.selector))
     if el.tag == 'input':
         # checkboxes or radios
         if el.attrib.get('type') in ('radio', 'checkbox'):
             return 'checked' in el.attrib
         # regular text input
         elif el.attrib.get('type', '') in ('', 'text', 'email', 'search', 'tel', 'url'):
             try:
                 return unicode(el.attrib['value'])
             except KeyError:
                 return self.default_or_raise(AttributeNotFound('Element %s does not have attribute value' % el))
         # TODO handle html5 number, datetime, etc.
         else:
             raise UnrecognizedElement('Element %s is recognized' % el)
     elif el.tag == 'textarea':
         return unicode(el.text)
     elif el.tag == 'select':
         options = el.xpath('.//option[@selected]')
         # default is the first one
         if len(options) == 0:
             options = el.xpath('.//option[1]')
         return u'\n'.join([unicode(o.text) for o in options])
     else:
         raise UnrecognizedElement('Element %s is recognized' % el)
开发者ID:P4ncake,项目名称:weboob,代码行数:28,代码来源:html.py

示例9: get_accounts_list

    def get_accounts_list(self):
        for table in self.doc.xpath('//div[@class="comptestabl"]/table'):
            try:
                account_type = self.ACCOUNT_TYPES[table.get('summary').lower()]
                if not account_type:
                    account_type = self.ACCOUNT_TYPES[table.xpath('./caption/text()')[0].strip().lower()]
            except (IndexError,KeyError):
                account_type = Account.TYPE_UNKNOWN
            for tr in table.xpath('./tbody/tr'):
                cols = tr.findall('td')

                link = cols[0].find('a')
                if link is None:
                    continue

                a = Account()
                a.type = account_type
                a.id = unicode(re.search('([A-Z\d]{4}[A-Z\d\*]{3}[A-Z\d]{4})', link.attrib['title']).group(1))
                a.label = unicode(link.attrib['title'].replace('%s ' % a.id, ''))
                tmp_balance = CleanText(None).filter(cols[1])
                a.currency = a.get_currency(tmp_balance)
                if not a.currency:
                    a.currency = u'EUR'
                a.balance = Decimal(Transaction.clean_amount(tmp_balance))
                a._has_cards = False
                a.url = urljoin(self.url, link.attrib['href'])
                yield a
开发者ID:P4ncake,项目名称:weboob,代码行数:27,代码来源:pro.py

示例10: get_account_status

 def get_account_status(self):
     return (
             StatusField(u'myname', u'My name', unicode(self.browser.get_my_name())),
             StatusField(u'score', u'Score', unicode(self.browser.score())),
             StatusField(u'avcharms', u'Available charms', unicode(self.browser.nb_available_charms())),
             StatusField(u'newvisits', u'New visits', unicode(self.browser.nb_new_visites())),
            )
开发者ID:laurentb,项目名称:weboob,代码行数:7,代码来源:module.py

示例11: iter_persons

    def iter_persons(self, pattern):
        params = [('partner', self.PARTNER_KEY),
                  ('q', pattern),
                  ('format', 'json'),
                  ('filter', 'person')]

        jres = self.__do_request('search', params)
        if jres is None:
            return
        if 'person' not in jres['feed']:
            return
        for p in jres['feed']['person']:
            thumbnail_url = NotAvailable
            if 'picture' in p:
                thumbnail_url = unicode(p['picture']['href'])
            person = Person(p['code'], unicode(p['name']))
            desc = u''
            if 'birthDate' in p:
                desc += '(%s), ' % p['birthDate']
            if 'activity' in p:
                for a in p['activity']:
                    desc += '%s, ' % a['$']
            person.real_name = NotLoaded
            person.birth_place = NotLoaded
            person.birth_date = NotLoaded
            person.death_date = NotLoaded
            person.gender = NotLoaded
            person.nationality = NotLoaded
            person.short_biography = NotLoaded
            person.short_description = desc.strip(', ')
            person.roles = NotLoaded
            person.thumbnail_url = thumbnail_url
            yield person
开发者ID:laurentb,项目名称:weboob,代码行数:33,代码来源:browser.py

示例12: edit_issue

    def edit_issue(self, issue, edit=True):
        backend = self.weboob.get_backend(issue.backend)
        content = self.issue2text(issue, backend)
        while True:
            if self.stdin.isatty():
                content = self.acquire_input(content, {'vim': "-c 'set ft=mail'"})
                m = message_from_string(content.encode('utf-8'))
            else:
                m = message_from_file(self.stdin)

            try:
                email_to = self.text2issue(issue, m)
            except ValueError as e:
                if not self.stdin.isatty():
                    raise
                input("%s -- Press Enter to continue..." % unicode(e).encode("utf-8"))
                continue

            try:
                issue = backend.post_issue(issue)
                print('Issue %s %s' % (self.formatter.colored(issue.fullid, 'red', 'bold'),
                                       'updated' if edit else 'created'))
                if edit:
                    self.format(issue)
                elif email_to:
                    self.send_notification(email_to, issue)
                return 0
            except IssueError as e:
                if not self.stdin.isatty():
                    raise
                input("%s -- Press Enter to continue..." % unicode(e).encode("utf-8"))
开发者ID:P4ncake,项目名称:weboob,代码行数:31,代码来源:boobtracker.py

示例13: iter_investment

    def iter_investment(self):
        for tr in self.doc.xpath("//table/tbody/tr[starts-with(@class, 'net2g_asv_tableau_ligne_')]"):
            cells = tr.findall('td')
            inv = self.create_investment(cells)
            inv.label = unicode(cells[self.COL_LABEL].xpath('a/span')[0].text.strip())
            inv.description = unicode(cells[self.COL_LABEL].xpath('a//div/b[last()]')[0].tail)

            yield inv
开发者ID:P4ncake,项目名称:weboob,代码行数:8,代码来源:accounts_list.py

示例14: load_state

    def load_state(self, state):
        super(LCLBrowser, self).load_state(state)

        # lxml _ElementStringResult were put in the state, convert them to plain strs
        # TODO to remove at some point
        if self.contracts:
            self.contracts = [unicode(s) for s in self.contracts]
        if self.current_contract:
            self.current_contract = unicode(self.current_contract)
开发者ID:laurentb,项目名称:weboob,代码行数:9,代码来源:browser.py

示例15: get_emissions

 def get_emissions(self, basename):
     params = [('partner', self.PARTNER_KEY),
               ('format', 'json'),
               ('filter', 'acshow'),
               ]
     result = self.__do_request('termlist', params)
     if result is None:
         return
     for emission in result['feed']['term']:
         yield Collection([basename, unicode(emission['nameShort'])], unicode(emission['$']))
开发者ID:laurentb,项目名称:weboob,代码行数:10,代码来源:browser.py


注:本文中的weboob.tools.compat.unicode函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。