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


Python xbmc.convertLanguage函数代码示例

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


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

示例1: _build_subtitle_list

    def _build_subtitle_list(self, search_results, item):
        results = []
        total_downloads = 0

        for result in search_results:
            lang3 = xbmc.convertLanguage(result["language"], xbmc.ISO_639_2)

            if lang3 in item["3let_language"]:
                total_downloads += result["downloads"]
                results.append({
                    'lang_index': item["3let_language"].index(lang3),
                    'filename': result["release"],
                    'language_name': xbmc.convertLanguage(result["language"], xbmc.ENGLISH_NAME),
                    'language_flag': result["language"],
                    'id': result["id"],
                    'rating': result["downloads"],
                    'sync': self._is_synced(item, result["video_file_size"], result["release"]),
                    'hearing_imp': False,
                    'is_preferred': lang3 == item['preferredlanguage']
                })

        # Fix the rating
        if total_downloads:
            for it in results:
                it["rating"] = min(int(round(it["rating"] / float(total_downloads), 1) * 8), 5)

        return sorted(results, key=lambda x: (x['is_preferred'], x['lang_index'], x['sync'], x['rating']), reverse=True)
开发者ID:CaTzil,项目名称:service.subtitles.napisy24pl,代码行数:27,代码来源:NapisyUtils.py

示例2: get_languages

def get_languages(params, lang_format = 2):
    """
    Get the requested languages the user want to search (3 letter format)

    Args:
        params: The passed parameters dict.
        lang_format: 0 to get full language name
            1 to get two letter code (ISO 639-1)
            2 to get three letter code (ISO 639-2/T or ISO 639-2/B) (default)

    Returns:
        An array with the requested languages, e.g. ['scc','eng']
    """
    langs = []  # ['scc','eng']
    for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
        if lang_format == 0:
            # Full language name
            langs.append(lang)
        elif lang_format == 1:
            # 2 letter format
            langs.append(xbmc.convertLanguage(lang, xbmc.ISO_639_1))
        else:
            # 3 letter format
            langs.append(xbmc.convertLanguage(lang, xbmc.ISO_639_2))
    return langs
开发者ID:iamninja,项目名称:script.service.brokensubs,代码行数:25,代码来源:subtitle.py

示例3: Search

def Search(item):
    d = timeout(set_filehash, args=(item["file_original_path"], item["rar"]), timeout_duration=15)
    md5hash = d.hexdigest()
    t = f(md5hash)
    filename = '.'.join(os.path.basename(item["file_original_path"]).split(".")[:-1])
    helper = NapiProjektHelper(filename, md5hash)
    results = helper.search(item, t)

    for result in results:
        listitem = xbmcgui.ListItem(label=xbmc.convertLanguage(result["language"], xbmc.ENGLISH_NAME),
                                    # language name for the found subtitle
                                    label2=filename,  # file name for the found subtitle
                                    iconImage="5",  # rating for the subtitle, string 0-5
                                    thumbnailImage=xbmc.convertLanguage(result["language"], xbmc.ISO_639_1)
                                    # language flag, ISO_639_1 language + gif extention, e.g - "en.gif"
                                    )
        listitem.setProperty("sync", '{0}'.format("true").lower())  # set to "true" if subtitle is matched by hash,
        # indicates that sub is 100 Comaptible
        listitem.setProperty("hearing_imp",
                             '{0}'.format("false").lower())  # set to "true" if subtitle is for hearing impared

        ## below arguments are optional, it can be used to pass any info needed in download function
        ## anything after "action=download&" will be sent to addon once user clicks listed subtitle to download
        url = "plugin://%s/?action=download&l=%s&f=%s&filename=%s" % (
            __scriptid__, result["language"], md5hash, filename)
        ## add it to list, this can be done as many times as needed for all subtitles found
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
开发者ID:NEOhidra,项目名称:service.subtitles.napiprojekt,代码行数:27,代码来源:service.py

示例4: _retrive_subtitles

 def _retrive_subtitles(self, page, item):
     ret = []
     total_downloads = 0
     if page is not None:
         found_subtitles = re.findall(
             'downloadsubtitle\.php\?id=(?P<fid>\d*).*?subt_lang.*?title="(?P<language>.*?)".*?subtitle_title.*?title="(?P<title>.*?)">.*?>(?P<downloads>[^ ]+) הורדות',
             page,
         )
         for (subtitle_id, language, title, downloads) in found_subtitles:
             if xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) in item["3let_language"]:
                 subtitle_rate = self._calc_rating(title, item["file_original_path"])
                 total_downloads += int(downloads.replace(",", ""))
                 ret.append(
                     {
                         "lang_index": item["3let_language"].index(
                             xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2)
                         ),
                         "filename": title,
                         "link": subtitle_id,
                         "language_name": xbmc.convertLanguage(heb_to_eng(language), xbmc.ENGLISH_NAME),
                         "language_flag": xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_1),
                         "ID": subtitle_id,
                         "rating": int(downloads.replace(",", "")),
                         "sync": subtitle_rate >= 4,
                         "hearing_imp": 0,
                     }
                 )
     return ret, total_downloads
开发者ID:roeiba,项目名称:xbmc,代码行数:28,代码来源:SUBUtilities.py

示例5: _retrive_subtitles

 def _retrive_subtitles(self, page, item):
     ret = []
     total_downloads = 0
     if page is not None:
         found_subtitles = re.findall(
             "downloadsubtitle\.php\?id=(?P<fid>\d*).*?subt_lang.*?title=\"(?P<language>.*?)\".*?subtitle_title.*?title=\"(?P<title>.*?)\">.*?>(?P<downloads>[^ ]+) הורדות",
             page)
         for (subtitle_id, language, title, downloads) in found_subtitles:
             if xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) in item[
                 "3let_language"]:
                 subtitle_rate = self._calc_rating(title, item["file_original_path"])
                 total_downloads += int(downloads.replace(",", ""))
                 ret.append(
                     {'lang_index': item["3let_language"].index(
                         xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2)),
                      'filename': title,
                      'link': subtitle_id,
                      'language_name': xbmc.convertLanguage(heb_to_eng(language),
                                                            xbmc.ENGLISH_NAME),
                      'language_flag': xbmc.convertLanguage(heb_to_eng(language),
                                                            xbmc.ISO_639_1),
                      'id': subtitle_id,
                      'rating': int(downloads.replace(",", "")),
                      'sync': subtitle_rate >= 3.8,
                      'hearing_imp': 0,
                      'is_preferred':
                          xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) == item['preferredlanguage']
                     })
     return ret, total_downloads
开发者ID:avi1951,项目名称:service.subtitles.subtitle,代码行数:29,代码来源:SUBUtilities.py

示例6: main

def main():
    """Main entry point of the script when it is invoked by XBMC."""

    # Get parameters from XBMC and launch actions
    params = get_params()

    if params['action'] == 'search':
        item = {}
        item['temp']               = False
        item['rar']                = False
        item['year']               = xbmc.getInfoLabel("VideoPlayer.Year")
        item['season']             = str(xbmc.getInfoLabel("VideoPlayer.Season"))
        item['episode']            = str(xbmc.getInfoLabel("VideoPlayer.Episode"))
        item['tvshow']             = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))
        # Try to get original title
        item['title']              = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle"))
        # Full path of a playing file
        item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8'))
        item['3let_language']      = []
        item['2let_language']      = []

        for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
            item['3let_language'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_2))
            item['2let_language'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_1))

        if not item['title']:
            # No original title, get just Title
            item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.Title"))

        if "s" in item['episode'].lower():
            # Check if season is "Special"
            item['season'] = "0"
            item['episode'] = item['episode'][-1:]

        if "http" in item['file_original_path']:
            item['temp'] = True

        elif "rar://" in item['file_original_path']:
            item['rar'] = True
            item['file_original_path'] = os.path.dirname(item['file_original_path'][6:])

        elif "stack://" in item['file_original_path']:
            stackPath = item['file_original_path'].split(" , ")
            item['file_original_path'] = stackPath[0][8:]

        Search(item)

    elif params['action'] == 'download':
        # We pickup all our arguments sent from def Search()
        subs = Download(params["id"], params["filename"])
        # We can return more than one subtitle for multi CD versions, for now
        # we are still working out how to handle that in XBMC core
        for sub in subs:
            listitem = xbmcgui.ListItem(label=sub)
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sub,
                                        listitem=listitem, isFolder=False)

    # Send end of directory to XBMC
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
开发者ID:mikellgonzalez,项目名称:service.subtitles.subdivx,代码行数:59,代码来源:service.py

示例7: search

def search():
    log( __name__, "action 'search' called")
    item = {}
    item['temp']               = False
    item['rar']                = False
    item['year']               = xbmc.getInfoLabel("VideoPlayer.Year")                           # Year
    item['season']             = str(xbmc.getInfoLabel("VideoPlayer.Season"))                    # Season
    item['episode']            = str(xbmc.getInfoLabel("VideoPlayer.Episode"))                   # Episode
    item['tvshow']             = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))   # Show
    item['title']              = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title
    item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8'))  # Full path of a playing file
    item['3let_language']      = []                                                              # ['scc','eng']
    for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
        item['3let_language'].append(xbmc.convertLanguage(lang,xbmc.ISO_639_2))
    if item['title'] == "":
        log( __name__, "VideoPlayer.OriginalTitle not found")
        item['title']  = normalizeString(xbmc.getInfoLabel("VideoPlayer.Title"))      # no original title, get just Title
    if item['episode'].lower().find("s") > -1:                                        # Check if season is "Special"
        item['season'] = "0"
        item['episode'] = item['episode'][-1:]
    if ( item['file_original_path'].find("http") > -1 ):
        item['temp'] = True
    elif ( item['file_original_path'].find("rar://") > -1 ):
        item['rar']  = True
        item['file_original_path'] = os.path.dirname(item['file_original_path'][6:])
    log( __name__, item)
    search_subtitles( item['file_original_path'], item['title'], item['tvshow'], item['year'], item['season'], item['episode'], item['3let_language'])
开发者ID:mr-blobby,项目名称:service.subtitles.bierdopje,代码行数:27,代码来源:service.py

示例8: search_by_language

def search_by_language(string, language):
  results     = []
  html_parser = HTMLParser.HTMLParser()

  if language in SUBTITLE_LANGUAGES:
    log('Searching for %s subtitles: %s' % (language, string))

    # Language specific stuff
    search_url    = SUBTITLE_LANGUAGES[language]['search_url']
    regex_pattern = SUBTITLE_LANGUAGES[language]['regex_pattern']
    priority      = SUBTITLE_LANGUAGES[language]['priority']

    # Get content
    content = get_content_from_url(search_url % urllib.quote(string.encode('latin')))

    # Parse results
    pattern = re.compile(regex_pattern)
    matches = pattern.finditer(content)

    # Loop through all matches
    for match in matches:
      results.append({
        'name'          : html_parser.unescape(match.group(2)).decode('latin'),
        'language'      : language,
        'language_code' : xbmc.convertLanguage(language, xbmc.ISO_639_1),
        'download_url'  : match.group(1),
        'priority'      : priority
      })
  else:
    log('Unsupported language: %s' % language)

  return results
开发者ID:luiangel,项目名称:Halowrepo,代码行数:32,代码来源:service.py

示例9: onPlayBackStarted

    def onPlayBackStarted(self):
        check_for_specific = (__addon__.getSetting('check_for_specific').lower() == 'true')
        specific_language = (__addon__.getSetting('selected_language'))
        specific_language = xbmc.convertLanguage(specific_language, xbmc.ISO_639_2)

        if self.run:
            movieFullPath = xbmc.Player().getPlayingFile()
            Debug("movieFullPath '%s'" % movieFullPath)
            xbmc.sleep(1000)
            availableLangs = xbmc.Player().getAvailableSubtitleStreams()
            Debug("availableLangs '%s'" % availableLangs)
            totalTime = xbmc.Player().getTotalTime()
            Debug("totalTime '%s'" % totalTime)
            videoclipAlbum = ''			
            if getSettingAsBool('ExcludeVideoClip'):
                videoclipAlbum = xbmc.InfoTagMusic.getAlbum()
                Debug("videoclipAlbum '%s'" % videoclipAlbum)
			
            if (xbmc.Player().isPlayingVideo() and totalTime > ExcludeTime and (not videoclipAlbum) and ((not xbmc.getCondVisibility("VideoPlayer.HasSubtitles")) or (check_for_specific and not specific_language in availableLangs)) and all(movieFullPath.find (v) <= -1 for v in ignore_words) and (isExcluded(movieFullPath)) ):
                self.run = False
                xbmc.sleep(1000)
                Debug('Started: AutoSearching for Subs')
                xbmc.executebuiltin('XBMC.ActivateWindow(SubtitleSearch)')
            else:
                Debug('Started: Subs found or Excluded')
                self.run = False
开发者ID:Mafarricos,项目名称:service.autosubs,代码行数:26,代码来源:default.py

示例10: search

def search(info, languages):
    """Add subtitles to the list using information gathered with get_info and get_languages"""
    logging.debug("---TUCAN---")
    logging.debug(info)
    url = addictedutils.build_show_url(
        addictedutils.get_show_id(info['tvshow']),
        info['season'],
        addictedutils.build_language_code_string(languages))
    logging.debug(url)
    subs = addictedutils.subs_array(url, info)
    #logging.debug(subs)
    for sub in subs:
        sub_name = sub['showTitle'] + " " + sub['season'] + "x" + sub['episode'] + " " + sub['version']
        sub_params = {
            "action": "download-addicted",
            "link": sub['link'],
            "name": sub_name
        }
        append_subtitle(
            sub_name,
            sub['lang'],
            xbmc.convertLanguage(sub['lang'], xbmc.ISO_639_2),
            sub_params,
            sub['sync'],
            sub['himp'])
开发者ID:iamninja,项目名称:script.service.brokensubs,代码行数:25,代码来源:subtitle.py

示例11: search

    def search(self, item, t, langs):

        fulllang = xbmc.convertLanguage(item['preferredlanguage'], xbmc.ENGLISH_NAME)
        if fulllang == "Persian": fulllang = "Farsi/Persian"
        #xbmc.executebuiltin("Notification(Title," + item['mansearchstr'] + ")")
        QueryString = self.filename;

        if item['mansearch']:
            QueryString = item['mansearchstr'];

        addon = xbmcaddon.Addon();

        if len(QueryString) < 6:
            xbmc.executebuiltin("Notification(" + addon.getLocalizedString(32003) + "," + addon.getLocalizedString(32002) + ")")
            return

        url = "http://www.subtitool.com/api/?query=" + QueryString + "&Lang=" + langs
        subs = urllib.urlopen(url).read()
        DOMTree = minidom.parseString(subs)
        if DOMTree.getElementsByTagName('Subtitle').length == 0:
           try:
            url = "http://www.subtitool.com/api/?query=" + QueryString + "&Lang=" + langs + "&OR=1"
            subs = urllib.urlopen(url).read()
            DOMTree = minidom.parseString(subs)
           except Exception, e:
                log("Subtitool","Not Found OR")

           try:
            url = "http://www.subtitool.com/api/?query=" + QueryString + "&Lang=" + langs
            subs = urllib.urlopen(url).read()
            DOMTree = minidom.parseString(subs)
           except Exception, e:
                log("Subtitool","Not Found")
开发者ID:KianMax,项目名称:service.subtitles.subtitool,代码行数:33,代码来源:SubTiTool.py

示例12: get_language

def get_language(abbrev):    
    try:
        lang_string = (key for key,value in LANGUAGES.items() if value == abbrev).next()
    except:
        lang_string = xbmc.convertLanguage(abbrev, xbmc.ENGLISH_NAME)
    if not lang_string:
        lang_string = 'n/a'
    return lang_string
开发者ID:mani49ers559,项目名称:PseudoTV_Live,代码行数:8,代码来源:language.py

示例13: search

	def search(self,item):

		if item['mansearch']:
			title = item['mansearchstr']
			dialog = xbmcgui.Dialog()
			item['season'] = dialog.numeric(0, self._t(32111), item['season'])
			item['episode'] = dialog.numeric(0, self._t(32112), item['episode'])
		else:
			title = self.normalize_input_title(item['tvshow'])
			if self.addon.getSetting("ignore_articles") == "true" and re.match(r'^The ',title,re.IGNORECASE):
				log(__name__, "Ignoring The in Title")
				title = re.sub(r'(?i)^The ',"", title)

		if not title or not item['season'] or not item['episode']:
			xbmc.executebuiltin("XBMC.Notification(%s,%s,5000,%s)" % (
						self.addon.getAddonInfo('name'), self._t(32110),
						os.path.join(xbmc.translatePath(self.addon.getAddonInfo('path')).decode("utf-8"),'icon.png')
			))
			log(__name__, ["Input validation error", title, item['season'], item['episode']])
			return results_with_stats(None, self.addon, title, item)

		tvshow_url = self.search_show_url(title)
		if tvshow_url == None: return results_with_stats(None, self.addon, title, item)

		file_size = get_file_size(item['file_original_path'], item['rar'])
		log(__name__, "File size: %s" % file_size)

		found_season_subtitles = self.search_season_subtitles(tvshow_url,item['season'])
		log(__name__, ["Season filter", found_season_subtitles])

		episode_subtitle_list = self.filter_episode_from_season_subtitles(found_season_subtitles,item['season'],item['episode'])
		log(__name__, ["Episode filter", episode_subtitle_list])
		if episode_subtitle_list == None: return results_with_stats(None, self.addon, title, item)

		lang_filetred_episode_subtitle_list = self.filter_subtitles_by_language(item['3let_language'], episode_subtitle_list)
		log(__name__, ["Language filter", lang_filetred_episode_subtitle_list])
		if lang_filetred_episode_subtitle_list == None: return results_with_stats(None, self.addon, title, item)

		max_down_count = self.detect_max_download_stats(lang_filetred_episode_subtitle_list)

		result_subtitles = []
		for episode_subtitle in lang_filetred_episode_subtitle_list['versions']:

			print_out_filename = episode_subtitle['rip'] + " by " + episode_subtitle['author']
			if episode_subtitle['notes']: print_out_filename += " (" + episode_subtitle['notes'] + ")"

			result_subtitles.append({
				'filename': HTMLParser.HTMLParser().unescape(print_out_filename),
				'link': episode_subtitle['link'],
				'lang': episode_subtitle['lang'],
				'rating': str(episode_subtitle['down_count']*5/max_down_count) if max_down_count > 0 else "0",
				'sync': (episode_subtitle['file_size'] == file_size and file_size > 0),
				'lang_flag': xbmc.convertLanguage(episode_subtitle['lang'],xbmc.ISO_639_1),
			})

		log(__name__,["Search result", result_subtitles])

		return results_with_stats(result_subtitles, self.addon, title, item)
开发者ID:beam,项目名称:service.subtitles.serialzone.cz,代码行数:58,代码来源:SerialZoneClient.py

示例14: display_movie

def display_movie(title, movieurl):
    divpname = re.search(r"/title/(.*.)", movieurl).group(1)
    log('MOVIE ID: %s' % divpname)
    (req, page) = load_url(movieurl)
    subtitles_list = []

    tb = page.find(id='subtable')
    links = tb.findAll('a', class_='download-btn')
    for link in links:
        addr = link['href']
        s_tr = link.find_parent('tr')
        tr_id = re.sub('row_id', '', s_tr['id'])
        s_tr2 = page.find('tr', id="row_id_alt%s" % tr_id)
        s_tr3 = page.find('tr', id="row_id_note%s" % tr_id)
        lantext = s_tr.find('img')['src']
        if lantext:
            if "en.png" in lantext:
                language = "English"
                lan_short = "en"
            elif "tr.png" in lantext:
                language = "Turkish"
                lan_short = "tr"
            else:
                raise ValueError("unsupported language: %s" % lantext)
            filename = u"%s.%s" % (title, lan_short)
            dtd = s_tr3.find('td').text
            description = dtd[dtd.index(' :') + 2:dtd.index(' - ')]
            log('description and filename:'),
            log(description)
            log(filename)
            l_item = xbmcgui.ListItem(
                label=language,  # language name for the found subtitle
                label2=description,  # file name for the found subtitle
                iconImage="0",  # rating for the subtitle, string 0-5
                thumbnailImage=xbmc.convertLanguage(language, xbmc.ISO_639_1)
            )

            # set to "true" if subtitle is for hearing impared
            l_item.setProperty("hearing_imp", '{0}'.format("false").lower())

            subtitles_list.append(l_item)

            url = "plugin://%s/?action=download&link=%s&lang=%s&description=%s&season=%s" % (
                __scriptid__,
                addr,
                lan_short,
                normalize_filename(filename),
                ""
            )

            xbmcplugin.addDirectoryItem(
                handle=int(sys.argv[1]),
                url=url,
                listitem=l_item,
                isFolder=False
            )
    log("PlanetDP: found %d subtitles from %s" % (len(subtitles_list), len(links)))
开发者ID:korayal,项目名称:service.subtitles.divxplanet,代码行数:57,代码来源:service.py

示例15: get_abbrev

def get_abbrev(lang_string):
    try:
        language_abbrev = xbmc.convertLanguage(lang_string, xbmc.ISO_639_1)
    except:
        language_abbrev = REAL_SETTINGS.getSetting('limit_preferred_language')
    if language_abbrev in LANGUAGES:
        return LANGUAGES[language_abbrev]
    else:
        language_abbrev = 'en' ### Default to English if conversion fails
    return language_abbrev
开发者ID:mani49ers559,项目名称:PseudoTV_Live,代码行数:10,代码来源:language.py


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