【推荐】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;

  }];

 

posted @ 2016-01-22 03:04  ForrestWoo  阅读(4576)  评论(1编辑  收藏  举报