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


Python util.translate函数代码示例

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


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


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