• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python compat.unicode函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: iter_transactions

 def iter_transactions(self):
     for li in self.doc.xpath('//section[@class="transactions"]//div/li'):
         date = li.xpath('p[@data-type="date"]//text()')[0].strip()
         label = li.xpath('p[@data-type="description"]//text()')[0].strip()
         amount = li.xpath('p[@data-type="amount"]//text()')[0].strip()
         t = Transaction()
         t.date = datetime.strptime(date, '%m/%d/%Y')
         t.rdate = datetime.strptime(date, '%m/%d/%Y')
         t.type = Transaction.TYPE_UNKNOWN
         t.raw = unicode(label)
         t.label = unicode(label)
         t.amount = -AmTr.decimal_amount(amount)
         yield t
开发者ID:laurentb,项目名称:weboob,代码行数:13,代码来源:browser.py


示例17: parse_video

 def parse_video(self, _video, category):
     video = BaseVideo(u'%s#%s' % (_video['code'], category))
     video.title = unicode(_video['title'])
     video._video_code = unicode(_video['code'])
     video.ext = u'mp4'
     if 'runtime' in _video:
         video.duration = timedelta(seconds=int(_video['runtime']))
     if 'description' in _video:
         video.description = unicode(_video['description'])
     renditions = sorted(_video['rendition'],
                         key=lambda x: 'bandwidth' in x and x['bandwidth']['code'],
                         reverse=True)
     video.url = unicode(max(renditions, key=lambda x: 'bandwidth' in x)['href'])
     return video
开发者ID:laurentb,项目名称:weboob,代码行数:14,代码来源:browser.py


示例18: obj_url

 def obj_url(self):
     links = XPath('//div[@id="download_links"]/div[@class="paragraph"]/div[has-class("share")]/a[@target="_blank"]/@href')(self)
     for link in links:
         ext = str(link).split('.')[-1]
         self.logger.debug("Link:%s Ext:%s", link, ext)
         if ext in ['mp4', 'webm']:
             return self.page.browser.BASEURL + unicode(link)
开发者ID:laurentb,项目名称:weboob,代码行数:7,代码来源:pages.py


示例19: update

    def update(self, progress=PrintProgress()):
        """
        Update repositories and install new packages versions.

        :param progress: observer object.
        :type progress: :class:`IProgress`
        """
        self.update_repositories(progress)

        to_update = []
        for name, info in self.get_all_modules_info().items():
            if not info.is_local() and info.is_installed():
                if self.versions.get(name) != info.version:
                    to_update.append(info)

        if len(to_update) == 0:
            progress.progress(1.0, 'All modules are up-to-date.')
            return

        class InstallProgress(PrintProgress):
            def __init__(self, n):
                self.n = n

            def progress(self, percent, message):
                progress.progress(float(self.n)/len(to_update) + 1.0/len(to_update)*percent, message)

        for n, info in enumerate(to_update):
            inst_progress = InstallProgress(n)
            try:
                self.install(info, inst_progress)
            except ModuleInstallError as e:
                inst_progress.progress(1.0, unicode(e))
开发者ID:laurentb,项目名称:weboob,代码行数:32,代码来源:repositories.py


示例20: retrieve_keyring

    def retrieve_keyring(self, browser, keyring_path, progress):
        # ignore local
        if self.local:
            return

        keyring = Keyring(keyring_path)
        # prevent previously signed repos from going unsigned
        if not self.signed and keyring.exists():
            raise RepositoryUnavailable('Previously signed repository can not go unsigned')
        if not self.signed:
            return

        if not keyring.exists() or self.key_update > keyring.version:
            # This is a remote repository, download file
            try:
                keyring_data = browser.open(posixpath.join(self.url, self.KEYRING)).content
                sig_data = browser.open(posixpath.join(self.url, self.KEYRING + '.sig')).content
            except BrowserHTTPError as e:
                raise RepositoryUnavailable(unicode(e))
            if keyring.exists():
                if not keyring.is_valid(keyring_data, sig_data):
                    raise InvalidSignature('the keyring itself')
                progress.progress(0.0, 'The keyring was updated (and validated by the previous one).')
            elif not progress.prompt('The repository %s isn\'t trusted yet.\nFingerprint of keyring is %s\nAre you sure you want to continue?' % (self.url, hashlib.sha1(keyring_data).hexdigest())):
                raise RepositoryUnavailable('Repository not trusted')
            keyring.save(keyring_data, self.key_update)
            progress.progress(0.0, str(keyring))
开发者ID:laurentb,项目名称:weboob,代码行数:27,代码来源:repositories.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python compat.urljoin函数代码示例发布时间:2022-05-26
下一篇:
Python virtkeyboard.MappedVirtKeyboard类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap