當前位置: 首頁>>代碼示例>>Python>>正文


Python langdetect.detect方法代碼示例

本文整理匯總了Python中langdetect.detect方法的典型用法代碼示例。如果您正苦於以下問題:Python langdetect.detect方法的具體用法?Python langdetect.detect怎麽用?Python langdetect.detect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在langdetect的用法示例。


在下文中一共展示了langdetect.detect方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: google_translate

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def google_translate(link):
    translator = Translator()	 # Google Translate API 
    pystring = " ".join(link[1:-2])
    lang = detect(pystring)
    if link[-1] == "english":
        id = "en"
    elif link[-1] == "spanish":
        id = "es"
    elif link[-1] == "french":
        id = "fr"
    elif link[-1] == "german":
        id = "de"
    elif link[-1] == "italian":
        id = "it"
    elif link[-1] == "portugese" or link[-1] == "portuguese":
        id = "pt"
    else:
        id = "en"
    translated = translator.translate(pystring, src=lang, dest=id)	# To Translate the given language to the required language
    print(translated.text)	# Print the translated script
    try:
        speak.say("The translated text is "+translated.text)
        speak.runAndWait()
    except:
        print("Error speaking, here is the translated text: {}".format(translated.text)) 
開發者ID:the-ethan-hunt,項目名稱:B.E.N.J.I.,代碼行數:27,代碼來源:google_translator.py

示例2: tag_reviews_language

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def tag_reviews_language(self):

        print('%s: tag reviews language' % time.strftime("%Y/%m/%d-%H:%M:%S"))

        if os.path.exists(Constants.LANGUAGE_RECORDS_FILE):
            print('Records have already been tagged with language field')
            self.records = \
                ETLUtils.load_json_file(Constants.LANGUAGE_RECORDS_FILE)
            return

        DetectorFactory.seed = 0

        for record in self.records:
            try:
                language = langdetect.detect(record[Constants.TEXT_FIELD])
            except LangDetectException:
                language = 'unknown'
            record[Constants.LANGUAGE_FIELD] = language

        ETLUtils.save_json_file(Constants.LANGUAGE_RECORDS_FILE, self.records) 
開發者ID:melqkiades,項目名稱:yelp,代碼行數:22,代碼來源:reviews_preprocessor.py

示例3: translate

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def translate(message, cmd, option, text):
    """
    指定した文字列を翻訳する

    http://docs.microsofttranslator.com/text-translate.html#!/default/get_Translate
    """
    if text in ('help', 'list'):
        return

    lang = 'ja'
    if option:
        # 指定した言語に翻訳する
        _, lang = option.split('-', 1)
    elif detect(text) in ('ja', 'ko'):
        # 漢字が多いと日本語なのに ko と判定される
        # 日本語の場合は英語に翻訳する
        lang = 'en'

    url = API_BASE_URL + 'Translate'
    headers = {
        'Ocp-Apim-Subscription-Key': settings.TRANSLATOR_API_KEY,
    }
    query = {
        'to': lang,
        'text': text,
    }
    r = requests.get(url, headers=headers, params=query)

    if r.status_code == 400:
        # エラーが発生したので內容を表示する
        error_message = r.text
        if "Message: 'to' must be a valid language" in error_message:
            botsend(message, '`{}` は無効な言語です'.format(lang))
        else:
            botsend(message, 'エラーが発生しました\n```\n{}\n```'.format(r.text))
        return

    tree = ET.fromstring(r.text)
    botsend(message, tree.text) 
開發者ID:pyconjp,項目名稱:pyconjpbot,代碼行數:41,代碼來源:translator.py

示例4: language

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def language(text, override_language=None):
    if override_language:
        return override_language

    try:
        return detect(text)
    except LangDetectException:
        return 'en' 
開發者ID:Sotera,項目名稱:pst-extraction,代碼行數:10,代碼來源:translation.py

示例5: detectLanguageAndEncode

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def detectLanguageAndEncode(s):
        # mod = importlib.import_module("langdetect")
        # detect_method = getattr(mod, "detect")
        # code = detect_method(s)
        from langdetect import detect
        code = detect(s)
        code_index = TextLangDetectTransformer.language_codes.index(
            code) if code in TextLangDetectTransformer.language_codes else -1
        return code_index 
開發者ID:h2oai,項目名稱:driverlessai-recipes,代碼行數:11,代碼來源:text_lang_detect_transformer.py

示例6: main

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def main(args): 

    with open(args.input[0], "r", errors='ignore') as frs:
        with open(args.input[1], "r", errors='ignore') as frt:
            data1 = [line for line in frs]
            data2 = [line for line in frt]

    if len(data1) != len(data2):
        print(len(data1), len(data2))
        raise ValueError("length of two files are not equal")

    src_lang = args.lang[0]
    trg_lang = args.lang[1]

    with open(args.input[0] + "." + args.suffix, "w") as fws:
        with open(args.input[1] + "." + args.suffix, "w") as fwt:
            for i in range(len(data1)):
                if i % 10000 == 0:
                    print(i, end = '\r')
                try:
                    line1 = data1[i].replace("@@ ", "")
                    line2 = data2[i].replace("@@ ", "")
                    length1 = len(line1.split(' '))
                    length2 = len(line2.split(' '))
                    if length1 / length2 < 0.7 or length2 / length1 < 0.7:
                        continue
                    if detect(line1) != src_lang or detect(line2) != trg_lang:
                        continue
                    fws.write(data1[i])
                    fwt.write(data2[i])
                except:
                    continue 
開發者ID:Imagist-Shuo,項目名稱:UNMT-SPR,代碼行數:34,代碼來源:clean_data.py

示例7: main

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def main():
    parent_dir = TRAIN_DIR / 'cmn'

    for target_file in ['tatoeba.txt', 'w2c.txt']:

        hant_file = open(TRAIN_DIR / 'cmn-hant' / target_file, mode='w')
        hans_file = open(TRAIN_DIR / 'cmn-hans' / target_file, mode='w')

        with open(parent_dir / target_file) as f:
            for line in f:
                text = line.rstrip()
                if not text:
                    continue

                try:
                    lang = langdetect.detect(text)
                except langdetect.lang_detect_exception.LangDetectException:
                    continue

                if lang in {'zh-tw', 'ko'}:
                    text = HanziConv.toTraditional(text)
                    hant_file.write(text)
                    hant_file.write('\n')
                elif lang == 'zh-cn':
                    text = HanziConv.toSimplified(text)
                    hans_file.write(text)
                    hans_file.write('\n')

        hant_file.close()
        hans_file.close() 
開發者ID:mhagiwara,項目名稱:nanigonet,代碼行數:32,代碼來源:clean_chinese.py

示例8: detect_lang

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def detect_lang(x):
    try:
        language = langdetect.detect(x)
    except:
        language = 'unk'
    return language


# language detection with textblob package 
開發者ID:kermitt2,項目名稱:delft,代碼行數:11,代碼來源:Utilities.py

示例9: get_response

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def get_response(self, query):
        try:
            probable_language = detect(query)
        except LangDetectException:
            probable_language = ""
        logging.info("Probable language is {}".format(probable_language))
        return self.get_response_from_chatbot(query, probable_language) 
開發者ID:freedomofkeima,項目名稱:messenger-maid-chan,代碼行數:9,代碼來源:chatbot.py

示例10: detect_language

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def detect_language(text):
    from langdetect import DetectorFactory, detect
    # Stay consistent between builds
    DetectorFactory.seed = 0

    return detect(text) 
開發者ID:mehdisadeghi,項目名稱:mehdix.ir,代碼行數:8,代碼來源:rebuild_comments.py

示例11: _safe_detect

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def _safe_detect(text):
    try:
        lang = detect(text)
    except Exception:
        lang = 'en'
    return lang 
開發者ID:minerva-ml,項目名稱:open-solution-toxic-comments,代碼行數:8,代碼來源:preprocessing.py

示例12: detect_language

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def detect_language(self):
    """Langdetect is non-deterministic, so to achieve a higher probability
    we attempt detection multiple times and only report success if we get identical results.
    """
    if self.language:
        return

    try:
        nondet_attempts = [detect(self.fulltext) for i in range(0,2)]
        is_unique = len(set(nondet_attempts)) == 1
        self.language = nondet_attempts[0] if is_unique else False
    except:
        pass 
開發者ID:fanmatics,項目名稱:metadoc,代碼行數:15,代碼來源:extractor.py

示例13: detect_language

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def detect_language(texts):
        texts = pd.Series(texts)
        language_codes = texts.apply(langdetect.detect).value_counts()
        return language_codes.index[0] 
開發者ID:HDI-Project,項目名稱:MLPrimitives,代碼行數:6,代碼來源:text.py

示例14: _remove_stopwords

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def _remove_stopwords(self, text):
        if text == '':
            return text

        if self.language_code:
            language_code = self.language_code

        elif self.language == 'multi':
            language_code = langdetect.detect(text)

        sw = self.get_stopwords(language_code)

        return ' '.join(word for word in text.split() if word not in sw) 
開發者ID:HDI-Project,項目名稱:MLPrimitives,代碼行數:15,代碼來源:text.py

示例15: separate_scripts

# 需要導入模塊: import langdetect [as 別名]
# 或者: from langdetect import detect [as 別名]
def separate_scripts(text, scripts):
    """
    Takes in a string and an iterable of language tags and returns an array of string paragraphs
    separated by language. The first language in scripts is the default. The paragraphs may be either
    html (separated by <p> or triple <br><br><br> tags) or text (separated by \n or dash).

    :param text: The plain text or html to separate paragraphs in by language.
    :param scripts: Iterable of allowed languages.
    :return:
    """
    # separate the text by paragraphs, matching to select html and plain text delimiters in data
    paragraphs = re.split(r'(</p><p>|\n|</p>|<p>| – |<br><br><br>)+', text)
    separated = {script: '' for script in scripts}
    # the first language given is the default one
    last_language = scripts[0]
    last_paragraph = ''
    for paragraph in paragraphs:
        if paragraph in (r'</p><p>', r'</p>' r'\n', r'<p>', r'<br><br><br>'):
            # skip paragraph breaks to prevent misdetection
            separated[last_language] += paragraph
            last_paragraph = paragraph
            continue
        # replace any misleading tags left
        paragraph_stripped = re.sub(r'(<(/)?strong>)|(<br>)+|&amp;|<a href=.*">|</a>', ' ', paragraph)
        try:
            language = detect(paragraph_stripped)
        except LangDetectException:
            # an exception means no language could be detected
            language = last_language
        # langdetect maps "Simplified Chinese" to "zh-cn"
        # However, we store it as "zh_hans"
        if language == "zh-cn":
            language = "zh_hans"
        if language not in scripts:
            # only detect allowed languages, no exceptions
            language = last_language
        if language != last_language:
            # fix html paragraph breaks after language change
            logger.debug('supported language detected: ' + language)
            if last_paragraph in (r'</p><p>', r'</p>', r'<p>'):
                separated[last_language] = re.sub(r'<p>$', '', separated[last_language])
                separated[language] += r'<p>'
            # remove useless dashes after language change
            if last_paragraph in (r' – ',):
                separated[last_language] = re.sub(r' – $', '', separated[last_language])
            # replace the awful triple-<br>
            if last_paragraph in (r'<br><br><br>',):
                separated[last_language] = re.sub(r'<br><br><br>$', '', separated[last_language])
                separated[last_language] += r'</p>'
                separated[language] += r'<p>'
        separated[language] += paragraph
        last_language = language
        last_paragraph = paragraph
    return separated 
開發者ID:City-of-Helsinki,項目名稱:linkedevents,代碼行數:56,代碼來源:util.py


注:本文中的langdetect.detect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。