[Visual Basic] 纯文本查看 复制代码
' 程序入口
Sub 全文替换()
For Each sentence In ActiveDocument.Sentences
If isEnglishSentence(sentence) Then
替换标点为英文 sentence
Else
替换标点为中文 sentence
End If
Next
End Sub
Sub 替换标点为英文(sentence)
Set re = CreateObject("VBScript.RegExp")
enArr = Array("-", ".", ",", ";", ":", "?", "!", "…", "~", "(", ")", "<", ">")
cnArr = Array("—", "。", ",", ";", ":", "?", "!", "……", "~", "(", ")", "《", "》")
re.Global = True
re.Pattern = "[" & Join(cnArr, "") & "]"
Set matches = re.Execute(sentence.Text)
For Each match In matches
ActiveDocument.Range(sentence.start + match.FirstIndex, sentence.start + match.FirstIndex + Len(match.Value)).Text = enArr(indexOf(cnArr, match.Value))
Next
End Sub
Sub 替换标点为中文(sentence)
Set re = CreateObject("VBScript.RegExp")
enArr = Array("-", ".", ",", ";", ":", "?", "!", "…", "~", "(", ")", "<", ">")
cnArr = Array("—", "。", ",", ";", ":", "?", "!", "……", "~", "(", ")", "《", "》")
re.Global = True
re.Pattern = "[-\\.,;:\\?!…~\\(\\)<>]"
Set matches = re.Execute(sentence.Text)
For Each match In matches
ActiveDocument.Range(sentence.start + match.FirstIndex, sentence.start + match.FirstIndex + Len(match.Value)).Text = cnArr(indexOf(enArr, match.Value))
Next
End Sub
Function isEnglishSentence(sentence As Variant)
Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.Pattern = "[\u4e00-\u9fa5]"
Set matches = re.Execute(sentence.Text)
If matches.Count > 0 Then
isEnglishSentence = False
Else
isEnglishSentence = True
End If
End Function
Function indexOf(arr, char)
For i = 0 To UBound(arr)
If arr(i) = char Then
indexOf = i
Exit Function
End If
Next
indexOf = -1
End Function