获取中文词组的汉语拼音首字母拼接

news2024/10/7 6:51:32

我们需要一个快捷批量处理:中文词组获取其汉语拼音首字母并拼接起来。

比如:

输出功率3:SCGL3

一鸣惊人:YMJR

我们可以采用字符字典法,穷举出所有的汉字【暂只考虑简体中文】

Dictionary<char,string> dict;

比如{'中',"Z"},

{'国',"G"},

{'人',"R"}

拼音Excel库【GBK汉字拼音对照表.xls】如下:

将其设置为 始终复制

添加对NPOI操作Excel的支持库

NpoiExcelOperateUtil.cs源程序如下:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChinesePinyinMappingDemo
{
    /// <summary>
    /// Excel表格与DataTable内存数据表的相互转换操作类
    /// 斯内科 2023-08-08
    /// </summary>
    public static class NpoiExcelOperateUtil
    {
        /// <summary>
        /// Excel的第一个工作簿(Sheet)转化成DataTable
        /// 使用EXCEL的第一个工作簿,默认为Sheet1
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx")
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else if (fileExt == ".xls")
                {
                    workbook = new HSSFWorkbook(fs);
                }
                else
                {
                    return null;
                }
                //第一个工作簿
                ISheet sheet = workbook.GetSheetAt(0);
                if (sheet == null)
                {
                    return null;
                }
                return ExcelToTable(file, sheet.SheetName);
            }
        }
        /// <summary>
        /// Excel的指定Sheet转化成内存表
        /// </summary>
        /// <param name="file">路径</param>
        /// <param name="sheetName">sheet名称</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file, string sheetName)
        {
            DataTable[] dataTables = ExcelToTable(file, new List<string>() { sheetName });
            if (dataTables != null && dataTables.Length > 0)
            {
                return dataTables[0];
            }
            return null;
        }

        /// <summary>
        /// 一个excel文件的多个Sheet转化成内存表数组,
        /// 每个Sheet都对应一个数据表
        /// </summary>
        /// <param name="file">路径</param>
        /// <param name="list_SheetName">sheet名称集合</param>
        /// <returns></returns>
        public static DataTable[] ExcelToTable(string file, List<string> list_SheetName)
        {
            int count = list_SheetName.Count;
            DataTable[] dtS = new DataTable[count];
            //===============================//
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx")
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else if (fileExt == ".xls")
                {
                    workbook = new HSSFWorkbook(fs);
                }
                else
                {
                    return null;
                }
                ISheet[] sheetS = new ISheet[count];
                for (int k = 0; k < count; k++)
                {
                    dtS[k] = new DataTable(list_SheetName[k]);
                    sheetS[k] = workbook.GetSheet(list_SheetName[k]);
                    ISheet sheet = sheetS[k];
                    if (sheet == null)
                    {
                        continue;
                    }
                    DataTable dt = new DataTable(list_SheetName[k]);
                    //表头  
                    IRow header = sheet.GetRow(sheet.FirstRowNum);
                    List<int> columns = new List<int>();
                    for (int i = 0; i < header.LastCellNum; i++)
                    {
                        object obj = GetValueType(header.GetCell(i));
                        if (obj == null || obj.ToString() == string.Empty)
                        {
                            dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                        }
                        else
                            dt.Columns.Add(new DataColumn(obj.ToString()));
                        columns.Add(i);
                    }
                    //数据  
                    for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                    {
                        DataRow dr = dt.NewRow();
                        bool hasValue = false;
                        foreach (int j in columns)
                        {
                            dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                            if (dr[j] != null && dr[j].ToString() != string.Empty)
                            {
                                hasValue = true;
                            }
                        }
                        if (hasValue)
                        {
                            dt.Rows.Add(dr);
                        }
                    }
                    dtS[k] = dt;
                }
            }
            return dtS;
        }

        /// <summary>
        /// Datable导出成Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="file"></param>
        public static void TableToExcel(DataTable dt, string file)
        {
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx")
            {
                //workbook = new XSSFWorkbook();
                workbook = new HSSFWorkbook();
            }
            else if (fileExt == ".xls")
            {
                workbook = new HSSFWorkbook();
            }
            else
            {
                workbook = null;
            }
            if (workbook == null)
            {
                return;
            }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);
            //表头  
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            //数据  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转为字节数组  
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件  
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }
    }
}

将默认的Form1重命名为FormChinesePinyinMapping,

FormChinesePinyinMapping设计器代码如下:

文件:FormChinesePinyinMapping.Designer.cs


namespace ChinesePinyinMappingDemo
{
    partial class FormChinesePinyinMapping
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.rtxtChinese = new System.Windows.Forms.RichTextBox();
            this.btnGetPinyin = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.rtxtResult = new System.Windows.Forms.RichTextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // rtxtChinese
            // 
            this.rtxtChinese.Location = new System.Drawing.Point(12, 43);
            this.rtxtChinese.Name = "rtxtChinese";
            this.rtxtChinese.Size = new System.Drawing.Size(536, 677);
            this.rtxtChinese.TabIndex = 0;
            this.rtxtChinese.Text = "";
            // 
            // btnGetPinyin
            // 
            this.btnGetPinyin.Location = new System.Drawing.Point(576, 57);
            this.btnGetPinyin.Name = "btnGetPinyin";
            this.btnGetPinyin.Size = new System.Drawing.Size(75, 23);
            this.btnGetPinyin.TabIndex = 1;
            this.btnGetPinyin.Text = "获取拼音";
            this.btnGetPinyin.UseVisualStyleBackColor = true;
            this.btnGetPinyin.Click += new System.EventHandler(this.btnGetPinyin_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 19);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(77, 12);
            this.label1.TabIndex = 2;
            this.label1.Text = "汉语拼接段落";
            // 
            // rtxtResult
            // 
            this.rtxtResult.Location = new System.Drawing.Point(688, 43);
            this.rtxtResult.Name = "rtxtResult";
            this.rtxtResult.Size = new System.Drawing.Size(536, 677);
            this.rtxtResult.TabIndex = 3;
            this.rtxtResult.Text = "";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(686, 19);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(101, 12);
            this.label2.TabIndex = 4;
            this.label2.Text = "拼音与拼音首字母";
            // 
            // FormChinesePinyinMapping
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1254, 732);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.rtxtResult);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.btnGetPinyin);
            this.Controls.Add(this.rtxtChinese);
            this.Name = "FormChinesePinyinMapping";
            this.Text = "汉字拼音对照表";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.RichTextBox rtxtChinese;
        private System.Windows.Forms.Button btnGetPinyin;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.RichTextBox rtxtResult;
        private System.Windows.Forms.Label label2;
    }
}

窗体FormChinesePinyinMapping代码如下:

文件:FormChinesePinyinMapping.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ChinesePinyinMappingDemo
{
    public partial class FormChinesePinyinMapping : Form
    {
        public FormChinesePinyinMapping()
        {
            InitializeComponent();
            rtxtChinese.Text = @"中国必须统一!
输出功率3
Nice!
上古十大神器:
东皇钟、昊天塔、盘古斧、轩辕剑、炼妖壶、
伏羲琴、神农鼎、崆峒印、昆仑镜、女娲石";
        }

        private void btnGetPinyin_Click(object sender, EventArgs e)
        {
            rtxtResult.Clear();
            string fileName = AppDomain.CurrentDomain.BaseDirectory + "GBK汉字拼音对照表.xls";
            DataTable dtImport = NpoiExcelOperateUtil.ExcelToTable(fileName);
            //元组的第一个元素代表汉字,第二个元素代表 第一读音,第三个元素代表拼音首字母
            //字典的键Key代表汉字,值Value是个元组 (第一读音,拼音首字母)
            Dictionary<char, Tuple<string, string>> chineseDictionary = dtImport.AsEnumerable().Select(dr => Tuple.Create(dr["汉字"].ToString().Trim().Length > 0 ? dr["汉字"].ToString().Trim()[0] : '\0',
    dr["第一读音"].ToString().Trim(), dr["第一读音"].ToString().Trim().Length > 0 ? dr["第一读音"].ToString().Trim().Substring(0, 1) : ""))
                .ToDictionary(tuple => tuple.Item1, tuple => Tuple.Create(tuple.Item2, tuple.Item3));
            //MessageBox.Show($"GBK汉字个数【{chineseDictionary.Count}】");
            string[] lines = rtxtChinese.Lines;
            for (int i = 0; i < lines.Length; i++)
            {
                rtxtResult.AppendText($"{GetSerialPinyin(lines[i], chineseDictionary)}\n");
            }
            rtxtResult.AppendText("----------获取拼音整体步骤------------\n");
            for (int i = 0; i < lines.Length; i++)
            {
                rtxtResult.AppendText($"{GetSerialFullPinyin(lines[i], chineseDictionary)}\n");
            }
        }

        /// <summary>
        /// 获取中文汉字的拼音首个字母【大写】,如果不是汉字(比如是英文或数字或标点符号等),则不做处理
        /// </summary>
        /// <param name="input"></param>
        /// <param name="chineseDictionary"></param>
        /// <returns></returns>
        private string GetFirstChar(char input, Dictionary<char, Tuple<string, string>> chineseDictionary) 
        {
            if (chineseDictionary.ContainsKey(input)) 
            {
                return chineseDictionary[input].Item2.ToUpper();
            }
            return input.ToString();
        }

        /// <summary>
        /// 获取一整段汉字并将其拼音首字母连接起来
        /// </summary>
        /// <param name="src"></param>
        /// <param name="chineseDictionary"></param>
        /// <returns></returns>
        private string GetSerialPinyin(string src, Dictionary<char, Tuple<string, string>> chineseDictionary) 
        {
            if (string.IsNullOrEmpty(src)) 
            {
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < src.Length; i++)
            {
                sb.Append(GetFirstChar(src[i], chineseDictionary));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 获取一行汉字的拼音(全拼)连接起来【首字母大写】
        /// </summary>
        /// <param name="src"></param>
        /// <param name="chineseDictionary"></param>
        /// <returns></returns>
        private string GetSerialFullPinyin(string src, Dictionary<char, Tuple<string, string>> chineseDictionary)
        {
            if (string.IsNullOrEmpty(src))
            {
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < src.Length; i++)
            {
                string singleChinese = src[i].ToString();
                if (chineseDictionary.ContainsKey(src[i]))
                {
                    //获取 第一读音
                    string fullPinyin = chineseDictionary[src[i]].Item1;
                    if (fullPinyin.Length > 0) 
                    {
                        //整体全拼 首字母大写
                        fullPinyin = fullPinyin[0].ToString().ToUpper() + fullPinyin.Substring(1);
                    }
                    singleChinese = fullPinyin;
                }
                sb.Append(singleChinese);
            }
            return sb.ToString();
        }
    }
}

测试运行如图:

(我们发现:女娲石,应为NWS,但显示为NWD,因我们只考虑第一个读音石:dan)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1017699.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【数据分享】2006-2021年我国省份级别的市容环境卫生相关指标(20多项指标)

《中国城市建设统计年鉴》中细致地统计了我国城市市政公用设施建设与发展情况&#xff0c;在之前的文章中&#xff0c;我们分享过基于2006-2021年《中国城市建设统计年鉴》整理的2006—2021年我国省份级别的市政设施水平相关指标、2006-2021年我国省份级别的各类建设用地面积数…

【C++】STL—— unordered_map的介绍和使用、 unordered_map的构造函数和迭代器、 unordered_map的增删查改函数

文章目录 1. unordered_map的介绍2. unordered_map的使用2.1unordered_map的构造函数2.2unordered_map的迭代器2.3unordered_map的容量和访问函数2.4unordered_map的增删查改函数 1. unordered_map的介绍 unordered_map的介绍 &#xff08;1&#xff09;unordered_map是存储&l…

ElasticSearch(ES)简答了解

ES简介 Elasticsearch&#xff08;通常简称为ES&#xff09;是一个开源的分布式搜索和分析引擎&#xff0c;旨在处理各种类型的数据&#xff0c;包括结构化、半结构化和非结构化数据。它最初是为全文搜索而设计的&#xff0c;但随着时间的推移&#xff0c;它已经演变成一个功能…

web系统安全设计原则

一、前言 近日&#xff0c;针对西工大网络被攻击&#xff0c;国家计算机病毒应急处理中心和360公司对一款名为“二次约会”的间谍软件进行了技术分析。分析报告显示&#xff0c;该软件是美国国家安全局&#xff08;NSA&#xff09;开发的网络间谍武器。当下&#xff0c;我们发现…

【骑行之旅】昆明草海湿地公园和海晏村的美丽邂逅

这是一个九月的星期六&#xff0c;在昆明的大观公园门口&#xff0c;我们集合了一群热爱骑行的骑友。今天&#xff0c;阳光明媚&#xff0c;天空湛蓝&#xff0c;一切都充满了活力。我们的旅程从这里开始&#xff0c;一路向西&#xff0c;向着下一站&#xff0c;美丽的草海湿地…

虚拟机用户切换及设置root权限的密码

天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物。 每个人都有惰性&#xff0c;但不断学习是好好生活的根本&#xff0c;共勉&#xff01; 文章均为学习整理笔记&#xff0c;分享记录为主&#xff0c;如有错误请指正&#xff0c;共同学习进步。…

驱动开发,IO多路复用(select,poll,epoll三种实现方式的比较)

1.IO多路复用介绍 在使用单进程或单线程情况下&#xff0c;同时处理多个输入输出请求&#xff0c;需要用到IO多路复用&#xff1b;IO多路复用有select/poll/epoll三种实现方式&#xff1b;由于不需要创建新的进程和线程&#xff0c;减少了系统资源的开销&#xff0c;减少了上下…

从0到1搭建Halo博客系统教程

前期准备 云服务器&#xff0c;域名&#xff0c;命令工具&#xff08;这里使用是Mobaxterm&#xff09; 安装环境 宝塔面板 yum install -y wget && wget -O install.sh https://download.bt.cn/install/install_6.0.sh && sh install.sh ed8484bec在命令工…

【计算机视觉】Image Generation Models算法介绍合集

文章目录 一、Diffusion二、Guided Language to Image Diffusion for Generation and Editing&#xff08;GLIDE&#xff09;三、classifier-guidance四、Blended Diffusion五、DALLE 2六、AltDiffusion七、Group Decreasing Network八、Make-A-Scene九、Iterative Inpainting十…

c++ - 抽象类 和 使用多态当中一些注意事项

抽象类 纯虚函数 在虚函数的后面写上 0 &#xff0c;则这个函数为纯虚函数。 class A { public:virtual void func() 0; }; 纯虚函数不需要写函数的定义&#xff0c;他有类似声明一样的结构。 抽象类概念 我们把具有纯虚函数的类&#xff0c;叫做抽象类。 所谓抽象就是&a…

docker gitlab+jenkins搭建

一&#xff1a;gitlab搭建: 1&#xff1a;docker部署 2&#xff1a;修改root密码 3&#xff1a;创建普通账户 4&#xff1a;设置sshken 二&#xff1a;jenkins搭建 配置脚本 bash -x /var/jenkins_home/shell/game01.sh

图解数据结构

&#x1f31e;欢迎来到数据结构的世界 &#x1f308;博客主页&#xff1a;卿云阁 &#x1f48c;欢迎关注&#x1f389;点赞&#x1f44d;收藏⭐️留言&#x1f4dd; &#x1f31f;本文由卿云阁原创&#xff01; &#x1f4c6;首发时间&#xff1a;&#x1f339;2023年9月17日&…

【探索Linux】—— 强大的命令行工具 P.8(进程地址空间)

阅读导航 前言一、内存空间分布二、什么是进程地址空间1. 概念2. 进程地址空间的组成 三、进程地址空间的设计原理1. 基本原理2. 虚拟地址空间 概念 大小和范围 作用 虚拟地址空间的优点 3. 页表 四、为什么要有地址空间五、总结温馨提示 前言 前面我们讲了C语言的基础知识&am…

性能测试-性能调优主要方向和原则(15)

性能调优主要方向明确性能瓶颈之后,就需要进行性能调优了,调优主要从图所示的多个方向入手。能优化手段并不一定是独立应用的,在一次优化过程中很可能应用了多种优化技巧。 硬件层面优化 硬件层面优化更偏向于监控,当定位到硬件资源成为瓶颈后,更多是采用扩容等手段来解决…

代码随想录算法训练营第三十六天| 435. 无重叠区间 763.划分字母区间 56. 合并区间

今天的三道题目&#xff0c;都算是 重叠区间 问题&#xff0c;大家可以好好感受一下。 都属于那种看起来好复杂&#xff0c;但一看贪心解法&#xff0c;惊呼&#xff1a;这么巧妙&#xff01; 还是属于那种&#xff0c;做过了也就会了&#xff0c;没做过就很难想出来。 不过大…

synchronized实战:synchronized 锁升级过程

下面程序通过对加锁前后Object对象字节码的打印验证了对象由无锁到偏向锁的过程。 public class T01 {public static void main(String[] args) {Object o new Object();System.out.println(ClassLayout.parseInstance(o).toPrintable());o.hashCode();System.out.println(Cl…

Linux界的老古董

Slackware 是由 Patrick Volkerding 制作的 Linux 发行版&#xff0c;从 1993 年发布至今也一直在 Patrick 带领下进行维护。7 月 17 日&#xff0c;Slackware 才刚刚过完它 24 岁的生日&#xff0c;看似年纪轻轻的它&#xff0c;已然是 Linux 最古老的发行版。 Slackware 的发…

laravel框架 - 安装初步使用学习 composer安装

一、什么是laravel框架 Laravel框架可以开发各种不同类型的项目&#xff0c;内容管理系统&#xff08;Content Management System&#xff0c;CMS&#xff09;是一种比较典型的项目&#xff0c;常见的网站类型&#xff08;如门户、新闻、博客、文章等&#xff09;都可以利用CM…

【Linux学习笔记】权限

1. 普通用户和root用户权限之间的切换2. 权限的三个w2.1. 什么是权限&#xff08;what&#xff09;2.1.1. 用户角色2.1.2. 文件属性 2.2. 怎么操作权限呢&#xff1f;&#xff08;how&#xff09;2.2.1. ugo-rwx方案2.2.2. 八进制方案2.2.3. 文件权限的初始模样2.2.4. 进入一个…

Linux基础操作

ls [-a -l -h] [Linux路径] 当不使用选项和参数&#xff0c;直接使用ls命令本体&#xff0c;表示以平铺的方式&#xff1a;列出当前工作目录下的内容 ls -a -a表示all的意思&#xff0c;即列出所有文件&#xff08;包含隐藏的文件和文件夹&#xff09; ls -l 以竖列的形式展示信…