首页
/ ChinesePinyin 项目技术文档

ChinesePinyin 项目技术文档

2024-12-20 03:37:52作者:裴麒琰

1. 安装指南

通过 RubyGems 安装

你可以通过以下命令使用 RubyGems 安装 chinese_pinyin

gem install chinese_pinyin

通过 Gemfile 安装

如果你使用的是 Ruby 项目,可以在 Gemfile 中添加以下内容:

gem 'chinese_pinyin'

然后运行 bundle install 来安装依赖。

2. 项目的使用说明

通过 CLI 使用

chinese_pinyin 提供了命令行工具 ch2py,可以通过命令行直接将中文转换为拼音。以下是一些常用的命令行选项:

$ ch2py -h
Usage: ch2py [opts]
    -c, --camelcase                  Camelcase of each word
    -i, --stdin                      Read from stdard input
    -t, --tone                       Show tone at end of word
    -m, --tonemarks                  Show tone at top of letter, this
would cover -t option
    -s, --splitter <splitter>        Splitter of each word, use a space
by default
    -v, --version                    Show version
    -h, --help                       Show this help

$ ch2py 中文
zhong wen

通过代码使用

你也可以在 Ruby 代码中使用 chinese_pinyin 库。以下是一些示例代码:

require 'chinese_pinyin'

# 基本用法
Pinyin.t('中国')  # => "zhong guo"

# 自定义分隔符
Pinyin.t('中国', splitter: '-')  # => "zhong-guo"
Pinyin.t('中国', splitter: '')   # => "zhongguo"

# 显示声调
Pinyin.t('中国', tone: true)     # => "zhong1 guo2"
Pinyin.t('中国', tonemarks: true) # => "zhōng guó"

# 自定义处理拼音
Pinyin.t('北京') { |letters| letters[0].upcase }  # => 'BJ'
Pinyin.t('北京') { |letters, i| letters[0].upcase if i == 0 }  # => 'B'

3. 项目API使用文档

Pinyin.t(text, options = {})

  • 参数:

    • text (String): 需要转换的中文字符串。
    • options (Hash): 可选参数,用于自定义转换行为。
      • splitter (String): 拼音之间的分隔符,默认为空格。
      • tone (Boolean): 是否在拼音后显示声调数字,默认为 false
      • tonemarks (Boolean): 是否在拼音字母上显示声调符号,默认为 false
  • 返回值:

    • (String): 转换后的拼音字符串。
  • 示例:

    Pinyin.t('中国', splitter: '-')  # => "zhong-guo"
    Pinyin.t('中国', tone: true)     # => "zhong1 guo2"
    

自定义多音字处理

chinese_pinyin 支持通过 Words.dat 文件自定义多音字的处理方式。你可以通过设置环境变量 WORDS_FILE 来指定 Words.dat 文件的路径。

ENV['WORDS_FILE'] = "Words.dat path"
Pinyin.t('广州')  # => "guang zhou"

4. 项目安装方式

通过 RubyGems 安装

gem install chinese_pinyin

通过 Gemfile 安装

Gemfile 中添加:

gem 'chinese_pinyin'

然后运行:

bundle install

通过以上步骤,你可以成功安装并使用 chinese_pinyin 项目。

登录后查看全文
热门项目推荐