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

Python util.translate函数代码示例

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

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



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

示例1: parse_album_xml

def parse_album_xml(text, album=None):
    """Parses the retrieved xml for an album and get's the track listing."""
    doc = minidom.parseString(text)
    
    album_item = doc.getElementsByTagName('Item')[0]
    try:
        tracklist = album_item.getElementsByTagName('Tracks')[0]
    except IndexError:
        write_log(translate('Amazon',
            'Invalid XML returned. No tracks listed.'))
        write_log(text)
        raise RetrievalError(translate('Amazon',
            'Invalid XML returned. No tracks listed.'))
    tracks = []
    discs = [disc for disc in tracklist.childNodes if 
        not disc.nodeType == disc.TEXT_NODE]
    if not (len(discs) > 1 and album):
        album = None
    for discnum, disc in enumerate(discs):
        for track_node in disc.childNodes:
            if track_node.nodeType == track_node.TEXT_NODE:
                continue
            title = get_text(track_node)
            tracknumber = track_node.attributes['Number'].value
            if album:
                tracks.append({'track': tracknumber, 'title': title,
                    'album': u'%s (Disc %s)' % (album, discnum + 1)})
            else:
                tracks.append({'track': tracknumber, 'title': title})
    return tracks
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:30,代码来源:amazon.py


示例2: search

    def search(self, album, artists=u'', limit=40):
        if time.time() - self.__lasttime < 1000:
            time.sleep(1)

        ret = []
        check_matches = False
        if isempty(artists):
            artist = None
        if len(artists) > 1:
            artist = u'Various Artists'
        elif artists:
            if hasattr(artists, 'items'):
                artist = artists.keys()[0]
            else:
                artist = artists[0]

        if not album and not artist:
            raise RetrievalError('Album or Artist required.')

        write_log(u'Searching for %s' % album)

        if hasattr(artists, "items"):
            album_id = find_id(chain(*artists.values()), "mbrainz_album_id")
            if album_id:
                try:
                    write_log(translate("MusicBrainz",
                        "Found album id %s in tracks. Retrieving") % album_id)
                    return [retrieve_album(album_id)]
                except RetrievalError, e:
                    msg = translate("MusicBrainz",
                        "<b>Error:</b> While retrieving Album ID %1 (%2)")
                    write_log(msg.arg(album_id).arg(escape(e)))
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:32,代码来源:musicbrainz.py


示例3: urlopen

def urlopen(url, mask=True, code=False):
    try:
        request = urllib2.Request(url)
        if useragent:
            request.add_header('User-Agent', useragent)
        page = urllib2.build_opener().open(request)
        if page.code == 403:
            raise RetrievalError(
                translate("Tag Sources", 'HTTPError 403: Forbidden'))
        elif page.code == 404:
            raise RetrievalError(
                translate("Tag Sources", "Page doesn't exist"))
        if code:
            return page.read(), page.code
        else:
            return page.read()
    except urllib2.URLError as e:
        try:
            msg = u'%s (%s)' % (e.reason.strerror, e.reason.errno)
        except AttributeError:
            msg = unicode(e)
        try:
            raise RetrievalError(msg, e.code)
        except AttributeError:
            raise RetrievalError(
                translate("Defaults", "Connection Error: %s ") % e.args[1])
    except socket.error as e:
        msg = u'%s (%s)' % (e.strerror, e.code)
        raise RetrievalError(msg)
    except EnvironmentError as e:
        msg = u'%s (%s)' % (e.strerror, e.code)
        raise RetrievalError(msg)
开发者ID:chincheta0815,项目名称:puddletag,代码行数:32,代码来源:__init__.py


示例4: search

    def search(self):
        if not self.searchButton.isEnabled():
            return
        files = self._status['selectedfiles']
        if self.curSource.group_by:
            group = split_by_field(files, *self.curSource.group_by)
        self.label.setText(translate("WebDB", 'Searching...'))
        text = None
        if self.searchEdit.text() and self.searchEdit.isEnabled():
            text = unicode(self.searchEdit.text())
        elif not files:
            self.label.setText(translate("WebDB",
                '<b>Select some files or enter search paramaters.</b>'))
            return

        def search():
            try:
                ret = []
                if text:
                    return self.curSource.keyword_search(text), None
                else:
                    return tag_source_search(self.curSource, group, files)
            except RetrievalError, e:
                return translate('WebDB',
                    'An error occured: %1').arg(unicode(e))
            except Exception, e:
                traceback.print_exc()
                return translate('WebDB',
                    'An unhandled error occurred: %1').arg(unicode(e))
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:29,代码来源:webdb.py


示例5: update_status

def update_status(enable = True):
    files = status['selectedfiles']
    pattern = status['patterntext']
    tf = lambda *args, **kwargs: encode_fn(findfunc.tagtofilename(*args, **kwargs))
    if not files:
        return
    tag = files[0]

    state = {'__counter': u'1', '__total_files': unicode(len(files))}

    x = findfunc.filenametotag(pattern, tag[PATH], True)
    emit('ftstatus', display_tag(x))

    bold_error = translate("Status Bar", "<b>%s</b>")
    
    try:
        newfilename = functions.move(tag, pattern, tag, state=state.copy())
        if newfilename:
            newfilename = newfilename['__path']
            emit('tfstatus', translate("Status Bar",
                "New Filename: <b>%1</b>").arg(
                    decode_fn(newfilename)))
        else:
            emit('tfstatus', u'<b>No change</b>')
    except findfunc.ParseError, e:
        emit('tfstatus', bold_error % e.message)
开发者ID:keithgg,项目名称:puddletag,代码行数:26,代码来源:funcs.py


示例6: number_tracks

def number_tracks(tags, offset, numtracks, restartdirs, padlength, split_field='__dirpath', output_field='track', by_group=False):
    """Numbers the selected tracks sequentially in the range
    between the indexes.
    The first item of indices is the starting track.
    The second item of indices is the number of tracks."""

    if not split_field:
        QMessageBox.critical(parent, translate("Autonumbering Wizard", 'Field empty...'),
                             translate("Autonumbering Wizard",
                                       "The field specified to use as a directory splitter was invalid. "
                                       "Please check your values."))
        return

    if not output_field:
        QMessageBox.critical(parent, translate("Autonumbering Wizard", 'Field empty...'),
                             translate("Autonumbering Wizard",
                                       "The output field specified was invalid. "
                                       "Please check your values."))
        return

    if restartdirs: #Restart dir numbering
        folders = OrderedDict()
        for tag_index, tag in enumerate(tags):
            key = findfunc.parsefunc(split_field, tag)
            if not isinstance(key, basestring):
                key = tag.stringtags().get(split_field)
            
            if key in folders:
                folders[key].append(tag_index)
            else:
                folders[key] = [tag_index]
    else:
        folders = {'fol': [i for i, t in enumerate(tags)]}


    taglist = {}
    for group_num, tags in enumerate(folders.itervalues()):
        if numtracks == -2:
            total = len(tags)
        elif numtracks is -1:
            total = None
        elif numtracks >= 0:
            total = numtracks
        for trknum, index in enumerate(tags):
            if by_group:
                trknum = group_num + offset
            else:
                trknum += offset
                
            text = _pad(trknum, total, padlength)
            taglist[index] = {output_field: text}

    taglist = [v for k,v in sorted(taglist.items(), key=lambda x: x[0])]

    emit('writeselected', taglist)
开发者ID:keithgg,项目名称:puddletag,代码行数:55,代码来源:funcs.py


示例7: retrieve_cover_links

def retrieve_cover_links(album_id, extra=None):
    if extra is None:
        url = "http://coverartarchive.org/release/" + album_id
    else:
        url = "http://coverartarchive.org/release/%s/%s" % (album_id, extra)
    write_log(translate("MusicBrainz", "Retrieving cover: %s") % url)
    try:
        data, code = urlopen(url, code=True)
    except RetrievalError, e:
        if e.code == 404:
            raise RetrievalError(translate("MusicBrainz",
                "No images exist for this album."), 404)
        raise e
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:13,代码来源:musicbrainz.py


示例8: load_musiclib

def load_musiclib(parent=None):
    try:
        m = puddlestuff.musiclib.LibChooseDialog(parent)
    except puddlestuff.musiclib.MusicLibError:
        QMessageBox.critical(parent, translate("MusicLib", 'No libraries found'),
           translate("MusicLib", "No supported music libraries were found. Most likely "
            "the required dependencies aren't installed. Visit the "
            "puddletag website, <a href='http://puddletag.sourceforge.net'>"
            "puddletag.sourceforge.net</a> for more details."))
        return
    m.setModal(True)
    obj.connect(m, SIGNAL('adddock'), emit_received('adddock'))
    m.show()
开发者ID:keithgg,项目名称:puddletag,代码行数:13,代码来源:funcs.py


示例9: load_mp3tag_sources

def load_mp3tag_sources(dirpath=MTAG_SOURCE_DIR):
    "Loads Mp3tag tag sources from dirpath and return the tag source classes."
    files = glob.glob(os.path.join(dirpath, '*.src'))
    classes = []
    for f in files:
        try:
            idents, search, album = mp3tag.open_script(f)
            classes.append(mp3tag.Mp3TagSource(idents, search, album))
        except:
            print translate("WebDB", "Couldn't load Mp3tag Tag Source %s") % f
            traceback.print_exc()
            continue
    return classes
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:13,代码来源:webdb.py


示例10: editItem

 def editItem(self, row=None):
     if row is None:
         row = self.listbox.currentRow()
     l = self.listbox.item
     patterns = [unicode(l(z).text()) for z in range(self.listbox.count())]
     (text, ok) = QInputDialog().getItem(self,
         translate("WebDB", 'Edit sort option'),
         translate("WebDB",
             'Enter a sorting option (a comma-separated list of fields. '
             'Eg. "artist, title")'), patterns, row)
     if ok:
         item = l(row)
         item.setText(text)
         self.listbox.setItemSelected(item, True)
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:14,代码来源:webdb.py


示例11: addPattern

 def addPattern(self):
     l = self.listbox.item
     patterns = [unicode(l(z).text()) for z in range(self.listbox.count())]
     row = self.listbox.currentRow()
     if row < 0:
         row = 0
     (text, ok) = QInputDialog().getItem(self, translate("WebDB",
         'Add sort option'),
         translate("WebDB",
             'Enter a sorting option (a comma-separated list of fields. '
             'Eg. "artist, title")'), patterns, row)
     if ok:
         self.listbox.clearSelection()
         self.listbox.addItem(text)
         self.listbox.setCurrentRow(self.listbox.count() - 1)
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:15,代码来源:webdb.py


示例12: parse_search_json

def parse_search_json(data):
    """Parses the xml retrieved after entering a search query. Returns a
    list of the albums found.
    """

    results = data.get('results', []) + data.get('exactresults', [])

    if not results:
        return []

    albums = []

    for result in results:
        info = result.copy()
        try:
            artist, album = result['title'].split(u' - ')
        except ValueError:
            album = result['title']
            artist = u''

        info = convert_dict(info, ALBUM_KEYS)

        info['artist'] = artist
        info['album'] = album

        info['discogs_id'] = info['#r_id']

        info['#extrainfo'] = (
            translate('Discogs', '%s at Discogs.com') % info['album'],
            SITE_URL + info['discogs_uri'])

        albums.append(check_values(info))

    return albums
开发者ID:chincheta0815,项目名称:puddletag,代码行数:34,代码来源:discogs.py


示例13: keyword_search

def keyword_search(keywords):
    write_log(translate("Discogs",
        'Retrieving search results for keywords: %s') % keywords)
    keywords = re.sub('(\s+)', u'+', keywords)
    url = search_url % keywords
    text = urlopen(url)
    return parse_search_json(json.loads(text))
开发者ID:kryger,项目名称:puddletag,代码行数:7,代码来源:discogs.py


示例14: library

 def library(self):
     dbpath = self.dbpath.text().toLocal8Bit()
     try:
         return QuodLibet(dbpath)
     except (IOError, OSError), e:
         raise MusicLibError(0, translate(
             "QuodLibet", '%1 (%2)').arg(e.strerror).arg(e.filename))
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:7,代码来源:quodlibetlib.py


示例15: select_db

 def select_db(self):
     filedlg = QFileDialog()
     filename = filedlg.getOpenFileName(self,
         translate("QuodLibet", 'Select QuodLibet library file...'),
         self.dbpath.text())
     if filename:
         self.dbpath.setText(filename)
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:7,代码来源:quodlibetlib.py


示例16: parse_search_xml

def parse_search_xml(text):
    """Parses the xml retrieved after entering a search query. Returns a
    list of the albums found.
    """
    doc = minidom.parseString(text)
    items = doc.getElementsByTagName('Item')
    ret = []
    for item in items:
        info = {}
        for attrib in item.getElementsByTagName('ItemAttributes'):
            if not check_binding(attrib):
                continue
            for child in attrib.childNodes:
                if child.nodeType == child.TEXT_NODE:
                    continue
                if child.tagName in XMLKEYS:
                    text_node = child.firstChild
                    if text_node.nodeType == text_node.TEXT_NODE:
                        info[XMLKEYS[child.tagName]] = text_node.data
        if not info:
            continue
        for key in IMAGEKEYS:
            image_items = item.getElementsByTagName(key)
            if image_items:
                info[IMAGEKEYS[key]] = get_image_url(image_items[0])
        info['#extrainfo'] = (translate('Amazon', '%s at Amazon.com') %
            info.get('album', u''), get_site_url(item))
        info['#asin'] = get_asin(item)
        info['asin'] = info['#asin']
        ret.append(info)
    return ret
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:31,代码来源:amazon.py


示例17: submit

 def submit():
     try:
         self.curSource.submit(files)
     except SubmissionError, e:
         traceback.print_exc()
         return translate('WebDB',
             'An error occured: %1').arg(unicode(e))
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:7,代码来源:webdb.py


示例18: parse_searchstring

def parse_searchstring(text):
    try:
        text = [z.split(u';') for z in text.split(u'|') if z]
        return [(z.strip(), v.strip()) for z, v in text]
    except ValueError:
        raise RetrievalError(translate('Tag Sources',
            '<b>Error parsing artist/album combinations.</b>'))
    return []
开发者ID:kryger,项目名称:puddletag,代码行数:8,代码来源:__init__.py


示例19: setResults

 def setResults(self, retval):
     self.searchButton.setEnabled(True)
     if isinstance(retval, (basestring, QString)):
         self.label.setText(retval)
     else:
         releases, files = retval
         if releases:
             self.label.setText(translate("WebDB",
                 'Searching complete.'))
         else:
             self.label.setText(translate("WebDB",
                 'No matching albums were found.'))
         if files and self.__autoRetrieve.isChecked():
             self.listbox.setReleases(releases, files)
         else:
             self.listbox.setReleases(releases)
         self.listbox.emit(SIGNAL('infoChanged'), '')
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:17,代码来源:webdb.py


示例20: keyword_search

 def keyword_search(self, s):
     if s.startswith(u':a'):
         artist_id = s[len(':a'):].strip()
         try:
             url = search_album('arid:' +
                 solr_escape(artist_id.encode('utf8')), limit=100, own=True)
             return parse_album_search(urlopen(url))
         except RetrievalError, e:
             msg = translate("MusicBrainz",
                 '<b>Error:</b> While retrieving %1: %2')
             write_log(msg.arg(artist_id).arg(escape(e)))
             raise
开发者ID:RaphaelRochet,项目名称:puddletag,代码行数:12,代码来源:musicbrainz.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python pulp.lpSum函数代码示例发布时间:2022-05-25
下一篇:
Python translations.translate函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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