You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将TrueType Macintosh语言代码转换为BCP 47语言标签的方法问询

Macintosh语言代码转BCP 47语言标签的可行方案

一、官方映射依据

Apple基于Unicode CLDR语言数据,维护了Macintosh语言代码与BCP 47标签的官方对应关系,该映射直接集成在系统框架中,覆盖所有标准Mac语言代码的转换场景,比如0对应en-US、1对应fr-FR、2对应de-DE等。

二、macOS原生API实现

借助CoreText和Foundation框架的API可直接完成转换,无需手动维护映射表,能自动处理区域变体、脚本差异等复杂情况:

Objective-C 示例代码

#import <CoreText/CoreText.h>
#import <Foundation/Foundation.h>

NSString *convertMacLangCodeToBCP47(UInt16 macLangCode) {
    CTFontDescriptorRef fontDescriptor = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)@{
        (id)kCTFontLanguageAttribute : @(macLangCode)
    });
    NSString *bcp47Tag = (__bridge_transfer NSString *)CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontLanguageAttribute);
    CFRelease(fontDescriptor);
    return bcp47Tag;
}

Swift 示例代码

import CoreText

func convertMacLangCodeToBCP47(_ macLangCode: UInt16) -> String? {
    let descriptorAttributes = [kCTFontLanguageAttribute as String: macLangCode] as CFDictionary
    guard let fontDescriptor = CTFontDescriptorCreateWithAttributes(descriptorAttributes),
          let bcp47Tag = CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontLanguageAttribute) as? String else {
        return nil
    }
    return bcp47Tag
}

三、跨环境的现成转换方案

如果需要脱离macOS环境处理,可使用以下方式:

  • 开源映射表:基于CLDR数据生成的Mac语言代码与BCP 47标签的映射表,可直接嵌入项目使用
  • 字体处理库:如Python的fonttools内置了转换逻辑,示例代码:
from fonttools.misc.maclang import mac_lang_to_bcp47

# 直接转换单个Mac语言代码
bcp47_tag = mac_lang_to_bcp47(0)  # 输出 "en-US"

内容的提问来源于stack exchange,提问作者jochen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:12:19