在 iOS 上使用 ML Kit 辨識文字語言
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
您可以使用 ML Kit 辨識文字字串的語言。你可以
取得最可能的語言,或是取得所有
字串的可能語言。
ML Kit 可辨識原生指令碼中 103 種不同語言的文字。
另外,阿拉伯文、保加利亞文、中文、
希臘文、北印度文、日文和俄文。
事前準備
- 如果尚未將 Firebase 加入應用程式,請按照下列步驟操作:
入門指南中的步驟。
- 在 Podfile 中加入 ML Kit 程式庫:
pod 'Firebase/MLNaturalLanguage', '6.25.0'
pod 'Firebase/MLNLLanguageID', '6.25.0'
敬上
安裝或更新專案的 Pod 後,請務必開啟 Xcode
專案 .xcworkspace
。
- 在應用程式中匯入 Firebase:
Objective-C
@import Firebase;
辨別字串的語言
如要識別字串語言,請取得
LanguageIdentification
,然後將字串傳遞至
identifyLanguage(for:)
方法。
例如:
Swift
let languageId = NaturalLanguage.naturalLanguage().languageIdentification()
languageId.identifyLanguage(for: text) { (languageCode, error) in
if let error = error {
print("Failed with error: \(error)")
return
}
if let languageCode = languageCode, languageCode != "und" {
print("Identified Language: \(languageCode)")
} else {
print("No language was identified")
}
}
Objective-C
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRLanguageIdentification *languageId = [naturalLanguage languageIdentification];
[languageId identifyLanguageForText:text
completion:^(NSString * _Nullable languageCode,
NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Failed with error: %@", error.localizedDescription);
return;
}
if (languageCode != nil
&& ![languageCode isEqualToString:@"und"] ) {
NSLog(@"Identified Language: %@", languageCode);
} else {
NSLog(@"No language was identified");
}
}];
如果呼叫成功,
BCP-47 語言代碼是
傳遞至完成處理常式,會指出文字的語言。詳情請參閱
支援語言的完整清單。如果答案為「否」
系統就能正確偵測語言,就會傳遞 und
(未判定) 程式碼。
根據預設,ML Kit 必須識別出非 und
值,才會傳回非 und
值
信賴價值至少為 0.5 的語言。您可以變更這個門檻
方法是將 LanguageIdentificationOptions
物件傳遞至
languageIdentification(options:)
:
Swift
let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)
let languageId = NaturalLanguage.naturalLanguage().languageIdentification(options: options)
Objective-C
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRLanguageIdentificationOptions *options =
[[FIRLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];
FIRLanguageIdentification *languageId =
[naturalLanguage languageIdentificationWithOptions:options];
取得字串的可能語言
如要針對字串最有可能的語言取得可信度值,請得到
LanguageIdentification
的例項,然後將該字串傳遞至
identifyPossibleLanguages(for:)
方法。
例如:
Swift
let languageId = NaturalLanguage.naturalLanguage().languageIdentification()
languageId.identifyPossibleLanguages(for: text) { (identifiedLanguages, error) in
if let error = error {
print("Failed with error: \(error)")
return
}
guard let identifiedLanguages = identifiedLanguages,
!identifiedLanguages.isEmpty,
identifiedLanguages[0].languageCode != "und"
else {
print("No language was identified")
return
}
print("Identified Languages:\n" +
identifiedLanguages.map {
String(format: "(%@, %.2f)", $0.languageCode, $0.confidence)
}.joined(separator: "\n"))
}
Objective-C
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRLanguageIdentification *languageId = [naturalLanguage languageIdentification];
[languageId identifyPossibleLanguagesForText:text
completion:^(NSArray<FIRIdentifiedLanguage *> * _Nonnull identifiedLanguages,
NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Failed with error: %@", error.localizedDescription);
return;
}
if (identifiedLanguages.count == 1
&& [identifiedLanguages[0].languageCode isEqualToString:@"und"] ) {
NSLog(@"No language was identified");
return;
}
NSMutableString *outputText = [NSMutableString stringWithFormat:@"Identified Languages:"];
for (FIRIdentifiedLanguage *language in identifiedLanguages) {
[outputText appendFormat:@"\n(%@, %.2f)", language.languageCode, language.confidence];
}
NSLog(outputText);
}];
如果呼叫成功,系統會將 IdentifiedLanguage
物件清單傳遞至
接續處理常式。您可以取得每個物件中語言的 BCP-47 程式碼
以該語言來說,這是很有信心的字串詳情請參閱
支援語言的完整清單。請注意,
這些值代表整個字串位於指定
語言;ML Kit 無法在單一字串中識別多種語言。
根據預設,ML Kit 只會傳回可信度值至少為
0.01。如要變更這個門檻,請傳送
將 LanguageIdentificationOptions
物件轉換為 languageIdentification(options:)
:
Swift
let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)
let languageId = NaturalLanguage.naturalLanguage().languageIdentification(options: options)
Objective-C
FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];
FIRLanguageIdentificationOptions *options =
[[FIRLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];
FIRLanguageIdentification *languageId =
[naturalLanguage languageIdentificationWithOptions:options];
如果沒有語言符合這項門檻,清單就會有一個項目,值
und
。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-16 (世界標準時間)。
[null,null,["上次更新時間:2025-08-16 (世界標準時間)。"],[],[],null,["You can use ML Kit to identify the language of a string of text. You can\nget the string's most likely language or get confidence scores for all of the\nstring's possible languages.\n\nML Kit recognizes text in 103 different languages in their native scripts.\nIn addition, romanized text can be recognized for Arabic, Bulgarian, Chinese,\nGreek, Hindi, Japanese, and Russian.\n\n\u003cbr /\u003e\n\nBefore you begin\n\n1. If you have not already added Firebase to your app, do so by following the steps in the [getting started guide](/docs/ios/setup).\n2. Include the ML Kit libraries in your Podfile: \n\n ```\n pod 'Firebase/MLNaturalLanguage', '6.25.0'\n pod 'Firebase/MLNLLanguageID', '6.25.0'\n ```\n After you install or update your project's Pods, be sure to open your Xcode project using its `.xcworkspace`.\n3. In your app, import Firebase: \n\n Swift \n\n ```swift\n import Firebase\n ```\n\n Objective-C \n\n ```objective-c\n @import Firebase;\n ```\n\nIdentify the language of a string\n\nTo identify the language of a string, get an instance of\n`LanguageIdentification`, and then pass the string to the\n`identifyLanguage(for:)` method.\n\nFor example: \n\nSwift \n\n let languageId = NaturalLanguage.naturalLanguage().languageIdentification()\n\n languageId.identifyLanguage(for: text) { (languageCode, error) in\n if let error = error {\n print(\"Failed with error: \\(error)\")\n return\n }\n if let languageCode = languageCode, languageCode != \"und\" {\n print(\"Identified Language: \\(languageCode)\")\n } else {\n print(\"No language was identified\")\n }\n }\n\nObjective-C \n\n FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];\n FIRLanguageIdentification *languageId = [naturalLanguage languageIdentification];\n\n [languageId identifyLanguageForText:text\n completion:^(NSString * _Nullable languageCode,\n NSError * _Nullable error) {\n if (error != nil) {\n NSLog(@\"Failed with error: %@\", error.localizedDescription);\n return;\n }\n if (languageCode != nil\n && ![languageCode isEqualToString:@\"und\"] ) {\n NSLog(@\"Identified Language: %@\", languageCode);\n } else {\n NSLog(@\"No language was identified\");\n }\n }];\n\nIf the call succeeds, a\n[BCP-47 language code](//en.wikipedia.org/wiki/IETF_language_tag) is\npassed to the completion handler, indicating the language of the text. See the\n[complete list of supported languages](/docs/ml-kit/langid-support). If no\nlanguage could be confidently detected, the code `und` (undetermined) is passed.\n\nBy default, ML Kit returns a non-`und` value only when it identifies the\nlanguage with a confidence value of at least 0.5. You can change this threshold\nby passing a `LanguageIdentificationOptions` object to\n`languageIdentification(options:)`: \n\nSwift \n\n let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)\n let languageId = NaturalLanguage.naturalLanguage().languageIdentification(options: options)\n\nObjective-C \n\n FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];\n FIRLanguageIdentificationOptions *options =\n [[FIRLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];\n FIRLanguageIdentification *languageId =\n [naturalLanguage languageIdentificationWithOptions:options];\n\nGet the possible languages of a string\n\nTo get the confidence values of a string's most likely languages, get an\ninstance of `LanguageIdentification`, and then pass the string to the\n`identifyPossibleLanguages(for:)` method.\n\nFor example: \n\nSwift \n\n let languageId = NaturalLanguage.naturalLanguage().languageIdentification()\n\n languageId.identifyPossibleLanguages(for: text) { (identifiedLanguages, error) in\n if let error = error {\n print(\"Failed with error: \\(error)\")\n return\n }\n guard let identifiedLanguages = identifiedLanguages,\n !identifiedLanguages.isEmpty,\n identifiedLanguages[0].languageCode != \"und\"\n else {\n print(\"No language was identified\")\n return\n }\n\n print(\"Identified Languages:\\n\" +\n identifiedLanguages.map {\n String(format: \"(%@, %.2f)\", $0.languageCode, $0.confidence)\n }.joined(separator: \"\\n\"))\n }\n\nObjective-C \n\n FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];\n FIRLanguageIdentification *languageId = [naturalLanguage languageIdentification];\n\n [languageId identifyPossibleLanguagesForText:text\n completion:^(NSArray\u003cFIRIdentifiedLanguage *\u003e * _Nonnull identifiedLanguages,\n NSError * _Nullable error) {\n if (error != nil) {\n NSLog(@\"Failed with error: %@\", error.localizedDescription);\n return;\n }\n if (identifiedLanguages.count == 1\n && [identifiedLanguages[0].languageCode isEqualToString:@\"und\"] ) {\n NSLog(@\"No language was identified\");\n return;\n }\n NSMutableString *outputText = [NSMutableString stringWithFormat:@\"Identified Languages:\"];\n for (FIRIdentifiedLanguage *language in identifiedLanguages) {\n [outputText appendFormat:@\"\\n(%@, %.2f)\", language.languageCode, language.confidence];\n }\n NSLog(outputText);\n }];\n\nIf the call succeeds, a list of `IdentifiedLanguage` objects is passed to the\ncontinuation handler. From each object, you can get the language's BCP-47 code\nand the confidence that the string is in that language. See the\n[complete list of supported languages](/docs/ml-kit/langid-support). Note that\nthese values indicate the confidence that the entire string is in the given\nlanguage; ML Kit doesn't identify multiple languages in a single string.\n\nBy default, ML Kit returns only languages with confidence values of at least\n0.01. You can change this threshold by passing a\n`LanguageIdentificationOptions` object to `languageIdentification(options:)`: \n\nSwift \n\n let options = LanguageIdentificationOptions(confidenceThreshold: 0.4)\n let languageId = NaturalLanguage.naturalLanguage().languageIdentification(options: options)\n\nObjective-C \n\n FIRNaturalLanguage *naturalLanguage = [FIRNaturalLanguage naturalLanguage];\n FIRLanguageIdentificationOptions *options =\n [[FIRLanguageIdentificationOptions alloc] initWithConfidenceThreshold:0.4];\n FIRLanguageIdentification *languageId =\n [naturalLanguage languageIdentificationWithOptions:options];\n\nIf no language meets this threshold, the list will have one item, with the value\n`und`."]]