【推薦】iOS漢字轉拼音第三方庫,ios漢字拼音第三方

來源:互聯網
上載者:User

【推薦】iOS漢字轉拼音第三方庫,ios漢字拼音第三方

  PinYin4Objc是一個在git漢字轉拼音的開源庫,支援簡體和繁體中文。效率POAPinyin等其他庫要高,轉換庫也完整下面簡單介紹

 

  實現原理

使用unicode_to_hanyu_pinyin.txt儲存漢字編碼相對應的拼音,以字典載入到記憶體中

 NSString *resourceName =[[NSBundle mainBundle] pathForResource:@"unicode_to_hanyu_pinyin" ofType:@"txt"];        NSString *dictionaryText=[NSString stringWithContentsOfFile:resourceName encoding:NSUTF8StringEncoding error:nil];        NSArray *lines = [dictionaryText componentsSeparatedByString:@"\r\n"];        __block NSMutableDictionary *tempMap=[[NSMutableDictionary alloc] init];        @autoreleasepool {                [lines enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {                    NSArray *lineComponents=[obj componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];                    [tempMap setObject:lineComponents[1] forKey:lineComponents[0]];                }];         }        self->_unicodeToHanyuPinyinTable=tempMap;        [self cacheObjec:self->_unicodeToHanyuPinyinTable forKey:kCacheKeyForUnicode2Pinyin];

 

 

當我們輸入漢字後,得到該漢字的編碼。下面圖為例。當我們點擊OK按鈕後

NSString *mainPinyinStrOfChar = [PinyinHelper getFirstHanyuPinyinStringWithChar:[str characterAtIndex:i] withHanyuPinyinOutputFormat:outputFormat];通過迴圈來產生漢字編碼

從字典中查詢key為“8F6C”的值為

取數組第一個就為拼音...

 

  使用

  1.下載庫

 

  2.引入標頭檔 #import "PinYin4Objc.h"

 

  3.建立拼音字元格式設定

  HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];

  格式包含ToneType,CharType,CaseType

typedef enum {  ToneTypeWithToneNumber,//有音調數字,如PIN1  ToneTypeWithoutTone,//無音調  ToneTypeWithToneMark}ToneType;
typedef enum {    CaseTypeUppercase,//拼音大小    CaseTypeLowercase// 拼音小寫}CaseType;
typedef enum {    VCharTypeWithUAndColon,    VCharTypeWithV,    VCharTypeWithUUnicode}VCharType;

 

 

   4.設定格式

    [outputFormat setToneType:ToneTypeWithoutTone];

    [outputFormat setVCharType:VCharTypeWithV];

    [outputFormat setCaseType:CaseTypeLowercase];

 

  5.調用toHanyuPinyinStringWithNSString:withHanyuPinyinOutputFormat:withNSString:outputBlock進行轉換

[PinyinHelper toHanyuPinyinStringWithNSString:sourceText withHanyuPinyinOutputFormat:outputFormat withNSString:@" " outputBlock:^(NSString *pinYin) {      _outputTv.text=pinYin;  }];

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.