zoukankan      html  css  js  c++  java
  • 【推荐】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:@"
    "];
            __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;
    
      }];
  • 相关阅读:
    Visual Studio 和 c# 正则表达式
    程序员DD 《Spring boot教程系列》补充
    c# 多线程编程中AutoResetEvent和ManualResetEvent
    c# 事件和EventManager
    卸载重装Mysql
    c# 语法要点速览
    在高分屏正确显示CHM文件
    ss user-rule自定义规则并硬连接到OneDrive进行自动同步
    利用webmagic获取天猫评论
    使用Selenium对新浪微博模拟登录
  • 原文地址:https://www.cnblogs.com/salam/p/5126053.html
Copyright © 2011-2022 走看看