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;
}];</pre> </div>