如何在Word文档中批量添加汉字注音
所谓的汉字注音,便是给汉字上方加注拼音。
在Office里面,这个功用叫做 “拼音攻略”(Phonetic Guide)。
拼音攻略一次只可以处理最多30个字,一篇文章不可能只要30个字,上百个字是很正常的,人工处理就会很累。所以,需要做到自动化,做到自动化有两种办法可以做到:
- 调用Office的功用;
- 直接修正docx文档。
调用Office的功用
调用Office的功用又有两个途径:
- VBA;
- .net。
其实,这两种途径终究都是调用的Office提供的API。
VBA
我查过了VBA的材料,总共有3个API可用:
- FormatPhoneticGuide
- Range.PhoneticGuide method (Word)
- Application.GetPhonetic method (Excel)
网上最多的用是第一种,运用FormatPhoneticGuide
宏,我试过是能用的,可是存在着一个很大的问题:它不可以定制拼音的款式。而且,相对来说不行安稳。
'Word批量运用默许款式加注拼音
Sub BatchAddPinYinByDefaultStyle()
On Error Resume Next
Selection.WholeStory
TextLength = Selection.Characters.Count
Selection.EndKey
For i = TextLength To 0 Step -30
If i < 30 Then
Selection.MoveLeft Unit:=wdCharacter, Count:=i
Selection.MoveRight(Unit:=wdCharacter, Count:=i,Extend:=wdExtend)
Else
Selection.MoveLeft Unit:=wdCharacter, Count:=30
Selection.MoveRight(Unit:=wdCharacter, Count:=30,Extend:=wdExtend)
End If
SendKeys "{Enter}"
Application.Run "FormatPhoneticGuide"
Next
Selection.WholeStory
End Sub
另外还有一个铲除注音的办法,用到了第二个API:
'Word批量铲除拼音
Sub CleanPinYin()
Application.ScreenUpdating = False
Selection.WholeStory
TextLength = Selection.Characters.Count
Selection.GoTo What:=wdGoToHeading, Which:=wdGoToAbsolute, Count:=1
For i = 0 To TextLength
With Selection
.Range.PhoneticGuide Text:=""
End With
Selection.MoveRight Unit:=wdCharacter, Count:=1
Next
Selection.WholeStory
Application.ScreenUpdating = True
End Sub
这一个API既可以铲除注音,也可以标明注音。只需要给Text赋值拼音即可。这个API好在可以定制拼音的款式,费事的是需要自己去核算出拼音,本来是找到了一个核算拼音的内置办法:GetPhonetic
,可是,它只存在于Excel里面,在Word里面无法进行调用。
要完成内置的GetPhonetic
,我在网上看到有两种完成办法:
- 自行完成的VBA,可是完成不行完整:github.com/StinkCat/CH…
- 运用golang写了一个RestFull服务器提供服务,然后提供给VBA调用:github.com/yangjianhua…
咱们来讨论第二种办法,比较灵敏。
首先是golang的拼音核算服务:
package main
import (
"flag"
"fmt"
"strconv"
"github.com/gin-gonic/gin"
"github.com/mozillazg/go-pinyin"
)
var a pinyin.Args
func initPinyinArgs(arg int) { // arg should be pinyin.Tone, pinyin.Tone1, pinyin.Tone2, pinyin.Tone3, see go-pinyin doc
a = pinyin.NewArgs()
a.Style = arg
}
func getPinyin(c *gin.Context) {
han := c.DefaultQuery("han", "")
p := pinyin.Pinyin(han, a)
c.JSON(200, gin.H{"code": 0, "data": p})
}
func getPinyinOne(c *gin.Context) {
han := c.DefaultQuery("han", "")
p := pinyin.Pinyin(han, a)
s := ""
if len(p) > 0 {
s = p[0][0]
}
c.JSON(200, gin.H{"code": 0, "data": s})
}
func allowCors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
func main() {
// init pinyin output format
initPinyinArgs(pinyin.Tone)
fmt.Print("\n\nDEFAULT PORT: 8080, USING '-port portnum' TO START ANOTHER PORT.\n\n")
port := flag.Int("port", 8080, "Port Number, default 8080")
flag.Parse()
sPort := ":" + strconv.Itoa(*port)
// using gin as a web output
r := gin.Default()
r.Use(allowCors())
r.GET("/pinyin", getPinyin) // Call like GET http://localhost:8080/pinyin?han=我来了
r.GET("/pinyin1", getPinyinOne)
r.Run(sPort)
}
接着,咱们来封装自己的GetPhonetic
:
'从Json字符串中提取data字段的数据
Function getDataFromJSON(s As String) As String
With CreateObject("VBScript.Regexp")
.Pattern = """data"":""(.*)"""
getDataFromJSON = .Execute(s)(0).SubMatches(0)
End With
End Function
'运用http组件调用拼音转换服务获取拼音字符
Function GetPhonetic(strWord As String) As String
Dim myURL As String
Dim winHttpReq As Object
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
myURL = "http://localhost:8080/pinyin1"
myURL = myURL & "?han=" & strWord
winHttpReq.Open "GET", myURL, False
winHttpReq.Send
GetPhonetic = getDataFromJSON(winHttpReq.responseText)
End Function
'测验GetPhonetic办法
Sub testGetPhonetic()
ret = GetPhonetic("汗")
MsgBox ret
End Sub
断定字符是否中文的办法:
'判别传入的Unicode是否为中文字符
Function isChinese(uniChar As Integer) As Boolean
isChinese = uniChar >= 19968 Or uniChar < 0
End Function
最终组装生成拼音注音的VBA脚本:
' Word批量拼音注音
' Alignment 对齐办法, see: https://learn.microsoft.com/en-us/office/vba/api/word.wdphoneticguidealignmenttype
' Raise 偏移量(磅)
' FontSize 字号(磅)
' FontName 字体
Sub BatchAddPinYin()
Application.ScreenUpdating = False
Dim SelectText As String
Dim PinYinText As String
Selection.WholeStory
TextLength = Selection.Characters.Count
Selection.GoTo What:=wdGoToHeading, Which:=wdGoToAbsolute, Count:=1
For i = 0 To TextLength
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
With Selection
SelectText = .Text '基准文字
If isChinese(AscW(SelectText)) Then '判别是否为中文字符
PinYinText = GetPhonetic(SelectText) '基准文字 转换为 拼音文字
If PinYinText <> "" Then
.Range.PhoneticGuide Text:=PinYinText, Alignment:=wdPhoneticGuideAlignmentCenter, _
Raise:=0, _
FontSize:=10, _
FontName:="等线"
End If
End If
End With
Selection.MoveRight Unit:=wdCharacter, Count:=1
Next
Selection.WholeStory
Application.ScreenUpdating = True
End Sub
根据golang服务代码的提供者所说,它比较显着的缺陷是对多音字的处理不如Word原来的拼音攻略,所以需要后期进行手工校对。
后期校对肯定是必须的,就好比古文里面还有一些通假字,发音是不一样的,这个,我想哪怕是拼音攻略也做不好的吧。
完整的BAS文件如下:
'判别传入的Unicode是否为中文字符
Function isChinese(uniChar As Integer) As Boolean
isChinese = uniChar >= 19968 Or uniChar < 0
End Function
'从Json字符串中提取data字段的数据
Function getDataFromJSON(s As String) As String
With CreateObject("VBScript.Regexp")
.Pattern = """data"":""(.*)"""
getDataFromJSON = .Execute(s)(0).SubMatches(0)
End With
End Function
'运用http组件调用拼音转换服务获取拼音字符
Function GetPhonetic(strWord As String) As String
Dim myURL As String
Dim winHttpReq As Object
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
myURL = "http://localhost:8080/pinyin1"
myURL = myURL & "?han=" & strWord
winHttpReq.Open "GET", myURL, False
winHttpReq.Send
GetPhonetic = getDataFromJSON(winHttpReq.responseText)
End Function
'测验GetPhonetic办法
Sub testGetPhonetic()
ret = GetPhonetic("汗")
MsgBox ret
End Sub
' Word批量拼音注音
' Alignment 对齐办法, see: https://learn.microsoft.com/en-us/office/vba/api/word.wdphoneticguidealignmenttype
' Raise 偏移量(磅)
' FontSize 字号(磅)
' FontName 字体
Sub BatchAddPinYin()
Application.ScreenUpdating = False
Dim SelectText As String
Dim PinYinText As String
Selection.WholeStory
TextLength = Selection.Characters.Count
Selection.GoTo What:=wdGoToHeading, Which:=wdGoToAbsolute, Count:=1
For i = 0 To TextLength
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
With Selection
SelectText = .Text '基准文字
If isChinese(AscW(SelectText)) Then '判别是否为中文字符
PinYinText = GetPhonetic(SelectText) '基准文字 转换为 拼音文字
If PinYinText <> "" Then
.Range.PhoneticGuide Text:=PinYinText, Alignment:=wdPhoneticGuideAlignmentCenter, _
Raise:=0, _
FontSize:=10, _
FontName:="等线"
End If
End If
End With
Selection.MoveRight Unit:=wdCharacter, Count:=1
Next
Selection.WholeStory
Application.ScreenUpdating = True
End Sub
'Word批量运用默许款式加注拼音
Sub BatchAddPinYinByDefaultStyle()
Application.ScreenUpdating = False
On Error Resume Next
Selection.WholeStory
TextLength = Selection.Characters.Count
Selection.EndKey
For i = TextLength To 0 Step -30
If i <= 30 Then
Selection.MoveLeft Unit:=wdCharacter, Count:=i
SelectText = Selection.MoveRight(Unit:=wdCharacter, Count:=i,Extend:=wdExtend)
Else
Selection.MoveLeft Unit:=wdCharacter, Count:=30
SelectText = Selection.MoveRight(Unit:=wdCharacter, Count:=30,Extend:=wdExtend)
End If
SendKeys "{Enter}"
Application.Run "FormatPhoneticGuide"
Next
Selection.WholeStory
Application.ScreenUpdating = True
End Sub
'Word批量铲除拼音注音
Sub CleanPinYin()
Application.ScreenUpdating = False
Selection.WholeStory
TextLength = Selection.Characters.Count
Selection.GoTo What:=wdGoToHeading, Which:=wdGoToAbsolute, Count:=1
For i = 0 To TextLength
With Selection
.Range.PhoneticGuide Text:=""
End With
Selection.MoveRight Unit:=wdCharacter, Count:=1
Next
Selection.WholeStory
Application.ScreenUpdating = True
End Sub
.net
它其实也是调用的Office的API,这个跟VBA调用API没有本质上的差异,是一样的。
VS2022需要装置:Visual Studio Tools for Office(VSTO)
然后,在项目当中引用程序集:Microsoft.Office.Interop.Word ,VS2022有14和15版本。
我本机的是Office16,而vs2022并没有提供相关的程序集,所以我没有办法运用,也就没有做进一步的探索了。
我查文档在Microsoft.Office.Interop.Word
命名空间下,有一个Range.PhoneticGuide办法,接口看起来跟VBA调用的差不多,运用上应该也是差不太多的。
直接修正docx文档
docx的文档本质上是一个经过了zip压缩的OpenXML文档。
基本上,主流的办公软件都支持这样一个标准:微软Office、苹果iWork、WPS Office、Google Docs。
拼音攻略在Office Open XML中的类型名是:CT_Ruby
。
Ruby,Wiki百科中解释为:注音,或称注音标识、加注音、标拼音、拼音攻略。
文档可见于:
- schemas.liquid-technologies.com/OfficeOpenX…
- learn.microsoft.com/zh-cn/dotne…
我略微研讨了下,拼音攻略的节点:<w:ruby>
。
其下面有若干个子节点:
-
<w:rubyPr>
是拼音攻略的款式, -
<w:rt>
是拼音攻略的拼音文字, -
<w:rubyBase>
是拼音攻略的基准文字。
一个比较完整的拼音攻略的XML是这样的:
<w:ruby>
<w:rubyPr>
<w:rubyAlign w:val="center"/>
<w:hps w:val="26"/>
<w:hpsRaise w:val="50"/>
<w:hpsBaseText w:val="52"/>
<w:lid w:val="zh-CN"/>
</w:rubyPr>
<w:rt>
<w:r w:rsidR="00002ED0" w:rsidRPr="00002ED0">
<w:rPr>
<w:rFonts w:ascii="等线" w:eastAsia="等线" w:hAnsi="等线"/>
<w:color w:val="333333"/>
<w:sz w:val="26"/>
<w:shd w:val="clear" w:color="auto" w:fill="FFFFFF"/>
</w:rPr>
<w:t>din</w:t>
</w:r>
</w:rt>
<w:rubyBase>
<w:r w:rsidR="00002ED0">
<w:rPr>
<w:rFonts w:ascii="华文楷体" w:eastAsia="华文楷体" w:hAnsi="华文楷体"/>
<w:color w:val="333333"/>
<w:sz w:val="52"/>
<w:shd w:val="clear" w:color="auto" w:fill="FFFFFF"/>
</w:rPr>
<w:t>点</w:t>
</w:r>
</w:rubyBase>
</w:ruby>
参考材料
- Office_Open_XML – WikiPedia
- 求解MacroName:=”FormatPhoneticGuide” ‘运行拼音攻略 在vba中的初始化办法
- 获取汉字拼音函数GetPhonetic的问题
- 有没有给大批量中文加拼音的宏?
- Word批量加注拼音/铲除拼音
- Add pinyin to all text using MS word.
- VBA实践+word快速全文加拼音