从数据挖掘到语言学习本身,文本分析功能的应用非常广泛,本一节我们来分析一个例子,它是文本分析最基本的一种形式:统计出一个文件里单词出现的频率。
示例中频率统计后的结果以两种不同的方式显示,一种是将单词按照字母顺序把单词和频率排列出来,另一种是按照有序列表的方式把频率和对应的单词显示出来,完整的示例代码如下所示:
~~~
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"unicode"
"unicode/utf8"
)
func main() {
if len(os.Args) == 1 || os.Args[1] == "-h" || os.Args[1] == "--help" {
fmt.Printf("usage: %s <file1> [<file2> [... <fileN>]]\n",
filepath.Base(os.Args[0]))
os.Exit(1)
}
frequencyForWord := map[string]int{} // 与:make(map[string]int)相同
for _, filename := range commandLineFiles(os.Args[1:]) {
updateFrequencies(filename, frequencyForWord)
}
reportByWords(frequencyForWord)
wordsForFrequency := invertStringIntMap(frequencyForWord)
reportByFrequency(wordsForFrequency)
}
func commandLineFiles(files []string) []string {
if runtime.GOOS == "windows" {
args := make([]string, 0, len(files))
for _, name := range files {
if matches, err := filepath.Glob(name); err != nil {
args = append(args, name) // 无效模式
} else if matches != nil {
args = append(args, matches...)
}
}
return args
}
return files
}
func updateFrequencies(filename string, frequencyForWord map[string]int) {
var file *os.File
var err error
if file, err = os.Open(filename); err != nil {
log.Println("failed to open the file: ", err)
return
}
defer file.Close()
readAndUpdateFrequencies(bufio.NewReader(file), frequencyForWord)
}
func readAndUpdateFrequencies(reader *bufio.Reader,
frequencyForWord map[string]int) {
for {
line, err := reader.ReadString('\n')
for _, word := range SplitOnNonLetters(strings.TrimSpace(line)) {
if len(word) > utf8.UTFMax ||
utf8.RuneCountInString(word) > 1 {
frequencyForWord[strings.ToLower(word)] += 1
}
}
if err != nil {
if err != io.EOF {
log.Println("failed to finish reading the file: ", err)
}
break
}
}
}
func SplitOnNonLetters(s string) []string {
notALetter := func(char rune) bool { return !unicode.IsLetter(char) }
return strings.FieldsFunc(s, notALetter)
}
func invertStringIntMap(intForString map[string]int) map[int][]string {
stringsForInt := make(map[int][]string, len(intForString))
for key, value := range intForString {
stringsForInt[value] = append(stringsForInt[value], key)
}
return stringsForInt
}
func reportByWords(frequencyForWord map[string]int) {
words := make([]string, 0, len(frequencyForWord))
wordWidth, frequencyWidth := 0, 0
for word, frequency := range frequencyForWord {
words = append(words, word)
if width := utf8.RuneCountInString(word); width > wordWidth {
wordWidth = width
}
if width := len(fmt.Sprint(frequency)); width > frequencyWidth {
frequencyWidth = width
}
}
sort.Strings(words)
gap := wordWidth + frequencyWidth - len("Word") - len("Frequency")
fmt.Printf("Word %*s%s\n", gap, " ", "Frequency")
for _, word := range words {
fmt.Printf("%-*s %*d\n", wordWidth, word, frequencyWidth,
frequencyForWord[word])
}
}
func reportByFrequency(wordsForFrequency map[int][]string) {
frequencies := make([]int, 0, len(wordsForFrequency))
for frequency := range wordsForFrequency {
frequencies = append(frequencies, frequency)
}
sort.Ints(frequencies)
width := len(fmt.Sprint(frequencies[len(frequencies)-1]))
fmt.Println("Frequency → Words")
for _, frequency := range frequencies {
words := wordsForFrequency[frequency]
sort.Strings(words)
fmt.Printf("%*d %s\n", width, frequency, strings.Join(words, ", "))
}
}
~~~
程序的运行结果如下所示。
~~~
PS D:\code> go run .\main.go small-file.txt
Word Frequency
ability 1
about 1
above 3
years 1
you 128
Frequency → Words
1 ability, about, absence, absolute, absolutely, abuse, accessible, ...
2 accept, acquired, after, against, applies, arrange, assumptions, ...
...
128 you
151 or
192 to
221 of
345 the
~~~
其中,small-file.txt 为待统计的文件名,它不是固定的,可以根据实际情况自行调整。由于输出的结果太多,所以上面只截取了部分内容。
通过上面的输出结果可以看出,第一种输出是比较直接的,我们可以使用一个`map[string]int`类型的结构来保存每一个单词的频率,但是要得到第二种输出结果我们需要将整个映射反转成多值类型的映射,如`map[int][]string`,也就是说,键是频率而值则是所有具有这个频率的单词。
接下来我们将从程序的 main() 函数开始,从上到下分析。
~~~
func main() {
if len(os.Args) == 1 || os.Args[1] == "-h" || os.Args[1] == "--help" {
fmt.Printf("usage: %s <file1> [<file2> [... <fileN>]]\n",
filepath.Base(os.Args[0]))
os.Exit(1)
}
frequencyForWord := map[string]int{} // 与:make(map[string]int)相同
for _, filename := range commandLineFiles(os.Args[1:]) {
updateFrequencies(filename, frequencyForWord)
}
reportByWords(frequencyForWord)
wordsForFrequency := invertStringIntMap(frequencyForWord)
reportByFrequency(wordsForFrequency)
}
~~~
main() 函数首先分析命令行参数,之后再进行相应处理。
我们使用复合语法创建一个空的映射,用来保存从文件读到的每一个单词和对应的频率,接着我们遍历从命令行得到的每一个文件,分析每一个文件后更新 frequencyForWord 的数据。
得到第一个映射之后,我们就可以输出第一个报告了(按照字母顺序排列的列表),然后我们创建一个反转的映射,输出第二个报告(按出现频率统计并排序的列表)。
~~~
func commandLineFiles(files []string) []string {
if runtime.GOOS == "windows" {
args := make([]string, 0, len(files))
for _, name := range files {
if matches, err := filepath.Glob(name); err != nil {
args = append(args, name) // 无效模式
} else if matches != nil {
args = append(args, matches...)
}
}
return args
}
return files
}
~~~
因为 Unix 类系统(如[Linux](http://c.biancheng.net/linux_tutorial/)或 Mac OS X 等)的命令行工具默认会自动处理通配符(也就是说,\*.txt 能匹配任意后缀为 .txt 的文件,如 README.txt 和 INSTALL.txt 等),而 Windows 平台的命令行工具(CMD)不支持通配符,所以如果用户在命令行输入 \*.txt,那么程序只能接收到 \*.txt。
为了保持平台之间的一致性,这里使用 commandLineFiles() 函数来实现跨平台的处理,当程序运行在 Windows 平台时,实现文件名通配功能。
~~~
func updateFrequencies(filename string, frequencyForWord map[string]int) {
var file *os.File
var err error
if file, err = os.Open(filename); err != nil {
log.Println("failed to open the file: ", err)
return
}
defer file.Close()
readAndUpdateFrequencies(bufio.NewReader(file), frequencyForWord)
}
~~~
updateFrequencies() 函数纯粹就是用来处理文件的,它打开给定的文件,并使用 defer 在函数返回时关闭文件,这里我们将文件作为一个 \*bufio.Reader(使用 bufio.NewReader() 函数创建)传给 readAndUpdateFrequencies() 函数,因为这个函数是以字符串的形式一行一行地读取数据的,所以实际的工作都是在 readAndUpdateFrequencies() 函数里完成的,代码如下。
~~~
func readAndUpdateFrequencies(reader *bufio.Reader, frequencyForWord map[string]int) {
for {
line, err := reader.ReadString('\n')
for _, word := range SplitOnNonLetters(strings.TrimSpace(line)) {
if len(word) > utf8.UTFMax || utf8.RuneCountInString(word) > 1 {
frequencyForWord[strings.ToLower(word)] += 1
}
}
if err != nil {
if err != io.EOF {
log.Println("failed to finish reading the file: ", err)
}
break
}
}
}
~~~
第一部分的代码我们应该很熟悉了,用了一个无限循环来一行一行地读一个文件,当读到文件结尾或者出现错误的时候就退出循环,将错误报告给用户但并不退出程序,因为还有很多其他的文件需要去处理。
任意一行都可能包括标点、数字、符号或者其他非单词字符,所以我们需要逐个单词地去读,将每一行分隔成若干个单词并使用 SplitOnNonLetters() 函数忽略掉非单词的字符,并且过滤掉字符串开头和结尾的空白。
只需要记录含有两个以上(包括两个)字母的单词,可以通过使用 if 语句,如 utf8.RuneCountlnString(word) > 1 来完成。
上面描述的 if 语句有一点性能损耗,因为它会分析整个单词,所以在这个程序里我们增加了一个判断条件,用来检査这个单词的字节数是否大于 utf8.UTFMax(utf8.UTFMax 是一个常量,值为 4,用来表示一个 UTF-8 字符最多需要几个字节)。
~~~
func SplitOnNonLetters(s string) []string {
notALetter := func(char rune) bool { return !unicode.IsLetter(char) }
return strings.FieldsFunc(s, notALetter)
}
~~~
SplitOnNonLetters() 函数用来在非单词字符上对一个字符串进行切分,首先我们为 strings.FieldsFunc() 函数创建一个匿名函数 notALetter,如果传入的是字符那就返回 false,否则返回 true,然后返回调用函数 strings.FieldsFunc() 的结果,调用的时候将给定的字符串和 notALetter 作为它的参数。
~~~
func reportByWords(frequencyForWord map[string]int) {
words := make([]string, 0, len(frequencyForWord))
wordWidth, frequencyWidth := 0, 0
for word, frequency := range frequencyForWord {
words = append(words, word)
if width := utf8.RuneCountInString(word); width > wordWidth {
wordWidth = width
}
if width := len(fmt.Sprint(frequency)); width > frequencyWidth {
frequencyWidth = width
}
}
sort.Strings(words)
gap := wordWidth + frequencyWidth - len("Word") - len("Frequency")
fmt.Printf("Word %*s%s\n", gap, " ", "Frequency")
for _, word := range words {
fmt.Printf("%-*s %*d\n", wordWidth, word, frequencyWidth,
frequencyForWord[word])
}
}
~~~
计算出了 frequencyForWord 之后,调用 reportByWords() 将它的数据打印出来,因为我们需要将输出结果按照字母顺序排序好,所以首先要创建一个空的容量足够大的 \[\]string 切片来保存所有在 frequencyForWord 里的单词。
第一个循环遍历映射里的所有项,把每个单词追加到 words 字符串切片里去,使用 append() 函数只需要把给定的单词追加到第 len(words) 个索引位置上即可,words 的长度会自动增加 1。
得到了 words 切片之后,对它进行排序,这个在 readAndUpdateFrequencies() 函数中已经处理好了。
经过排序之后我们打印两列标题,第一个是 "Word",为了能让 Frequency 最后一个字符 y 右对齐,需要在 "Word" 后打印一些空格,通过`%*s`可以实现的打印固定长度的空白,也可以使用`%s`来打印 strings.Repeat(" ", gap) 返回的字符串。
最后,我们将单词和它们的频率用两列方式按照字母顺序打印出来。
~~~
func invertStringIntMap(intForString map[string]int) map[int][]string {
stringsForInt := make(map[int][]string, len(intForString))
for key, value := range intForString {
stringsForInt[value] = append(stringsForInt[value], key)
}
return stringsForInt
}
~~~
上面的函数首先创建一个空的映射,用来保存反转的结果,但是我们并不知道它到底要保存多少个项,因此我们假设它和原来的映射容量一样大,然后简单地遍历原来的映射,将它的值作为键保存到反转的映射里,并将键增加到对应的值里去,新的映射的值就是一个字符串切片,即使原来的映射有多个键对应同一个值,也不会丢掉任何数据。
~~~
func reportByFrequency(wordsForFrequency map[int][]string) {
frequencies := make([]int, 0, len(wordsForFrequency))
for frequency := range wordsForFrequency {
frequencies = append(frequencies, frequency)
}
sort.Ints(frequencies)
width := len(fmt.Sprint(frequencies[len(frequencies)-1]))
fmt.Println("Frequency → Words")
for _, frequency := range frequencies {
words := wordsForFrequency[frequency]
sort.Strings(words)
fmt.Printf("%*d %s\n", width, frequency, strings.Join(words, ", "))
}
}
~~~
这个函数的结构和 reportByWords() 函数很相似,它首先创建一个切片用来保存频率,并按照频率升序排列,然后再计算需要容纳的最大长度并以此作为第一列的宽度,之后输出报告的标题,最后,遍历输出所有的频率并按照字母升序输出对应的单词,如果一个频率有超过两个对应的单词则单词之间使用逗号分隔开。
- 1.Go语言环境搭建
- 1.1 安装与环境
- 1.2 国内镜像配置
- 1.3 IDE的选择
- 2.Go语言基础语法
- 2.1 Go语言变量的声明
- 2.2 Go语言变量的初始化
- 2.3 Go语言多个变量同时赋值
- 2.4 Go语言匿名变量
- 2.5 Go语言变量的作用域
- 2.6 Go语言整型
- 2.7 Go语言浮点类型
- 2.8 Go语言复数
- 2.9 Go语言输出正弦函数(Sin)图像
- 2.10 Go语言bool类型
- 2.11 Go语言字符串
- 2.12 Go语言字符类型
- 2.13 Go语言数据类型转换
- 2.14 Go语言指针详解
- 2.15 Go语言变量逃逸分析
- 2.16 Go语言变量的生命周期
- 2.17 Go语言常量和const关键字
- 2.18 Go语言模拟枚举
- 2.19 Go语言type关键字
- 2.20 Go语言注释的定义及使用
- 2.21 Go语言关键字与标识符简述
- 2.22 Go语言运算符的优先级
- 2.23 Go语言strconv包
- 3.Go语言容器
- 3.1 Go语言数组详解
- 3.2 Go语言多维数组简述
- 3.3 Go语言切片详解
- 3.4 Go语言append()为切片添加元素
- 3.5 Go语言切片复制
- 3.6 Go语言从切片中删除元素
- 3.7 Go语言range关键字
- 3.8 Go语言多维切片简述
- 3.9 Go语言map
- 3.10 Go语言遍历map
- 3.11 Go语言map元素的删除和清空
- 3.12 Go语言sync.Map
- 3.13 Go语言list
- 3.14 Go语言nil
- 3.15 Go语言make和new关键字的区别及实现原理
- 4.Go语言流程控制
- 4.1 Go语言分支结构
- 4.2 Go语言循环结构
- 4.3 Go语言输出九九乘法表
- 4.4 Go语言键值循环
- 4.5 Go语言switch语句
- 4.6 Go语言goto语句
- 4.7 Go语言break
- 4.8 Go语言continue
- 4.9 Go语言聊天机器人
- 4.10 Go语言词频统计
- 4.11 Go语言缩进排序
- 4.12 Go语言实现二分查找算法
- 4.13 Go语言冒泡排序
- 5.Go语言函数
- 5.1 Go语言函数声明
- 5.2 Go语言将秒转换为具体的时间
- 5.3 Go语言函数中的参数传递效果测试
- 5.4 Go语言函数变量
- 5.5 Go语言字符串的链式处理
- 5.6 Go语言匿名函数
- 5.7 Go语言函数类型实现接口
- 5.8 Go语言闭包(Closure)
- 5.9 Go语言可变参数(变参函数)
- 5.10 Go语言defer(延迟执行语句)
- 5.11 Go语言递归函数
- 5.12 Go语言处理运行时错误
- 5.13 Go语言宕机(panic)
- 5.14 Go语言宕机恢复(recover)
- 5.15 Go语言计算函数执行时间
- 5.16 Go语言通过内存缓存来提升性能
- 5.17 Go语言函数的底层实现
- 5.18 Go语言Test功能测试函数详解
- 6.Go语言结构体
- 6.1 Go语言结构体定义
- 6.2 Go语言实例化结构体
- 6.3 Go语言初始化结构体的成员变量
- 6.4 Go语言构造函数
- 6.5 Go语言方法和接收器
- 6.6 Go语言为任意类型添加方法
- 6.7 Go语言使用事件系统实现事件的响应和处理
- 6.8 Go语言类型内嵌和结构体内嵌
- 6.9 Go语言结构体内嵌模拟类的继承
- 6.10 Go语言初始化内嵌结构体
- 6.11 Go语言内嵌结构体成员名字冲突
- 6.12 Go语言使用匿名结构体解析JSON数据
- 6.13 Go语言垃圾回收和SetFinalizer
- 6.14 Go语言将结构体数据保存为JSON格式数据
- 6.15 Go语言链表操作
- 6.16 Go语言数据I/O对象及操作
- 7.Go语言接口
- 7.1 Go语言接口声明
- 7.2 Go语言实现接口的条件
- 7.3 Go语言类型与接口的关系
- 7.4 Go语言类型断言简述
- 7.5 Go语言实现日志系统
- 7.6 Go语言排序
- 7.7 Go语言接口的嵌套组合
- 7.8 Go语言接口和类型之间的转换
- 7.9 Go语言空接口类型
- 7.10 Go语言使用空接口实现可以保存任意值的字典
- 7.11 Go语言类型分支
- 7.12 Go语言error接口
- 7.13 Go语言接口内部实现
- 7.14 Go语言表达式求值器
- 7.15 Go语言实现Web服务器
- 7.16 Go语言音乐播放器
- 7.17 Go语言实现有限状态机(FSM)
- 7.18 Go语言二叉树数据结构的应用
- 8.Go语言包
- 8.1 Go语言包的基本概念
- 8.2 Go语言封装简介及实现细节
- 8.3 Go语言GOPATH详解
- 8.4 Go语言常用内置包简介
- 8.5 Go语言自定义包
- 8.6 Go语言package
- 8.7 Go语言导出包中的标识符
- 8.8 Go语言import导入包
- 8.9 Go语言工厂模式自动注册
- 8.10 Go语言单例模式简述
- 8.11 Go语言sync包与锁
- 8.12 Go语言big包
- 8.13 Go语言使用图像包制作GIF动画
- 8.14 Go语言正则表达式
- 8.15 Go语言time包
- 8.16 Go语言os包用法简述
- 8.17 Go语言flag包
- 8.18 Go语言go mod包依赖管理工具使用详解
- 8.19 Go语言生成二维码
- 8.20 Go语言Context(上下文)
- 8.21 客户信息管理系统
- 8.22 Go语言发送电子邮件
- 8.23 Go语言(Pingo)插件化开发
- 8.24 Go语言定时器实现原理及作用
- 9.Go语言并发
- Go语言并发简述(并发的优势)
- Go语言goroutine(轻量级线程)
- Go语言并发通信
- Go语言竞争状态简述
- Go语言GOMAXPROCS(调整并发的运行性能)
- 并发和并行的区别
- goroutine和coroutine的区别
- Go语言通道(chan)——goroutine之间通信的管道
- Go语言并发打印(借助通道实现)
- Go语言单向通道——通道中的单行道
- Go语言无缓冲的通道
- Go语言带缓冲的通道
- Go语言channel超时机制
- Go语言通道的多路复用——同时处理接收和发送多个通道的数据
- Go语言RPC(模拟远程过程调用)
- Go语言使用通道响应计时器的事件
- Go语言关闭通道后继续使用通道
- Go语言多核并行化
- Go语言Telnet回音服务器——TCP服务器的基本结构
- Go语言竞态检测——检测代码在并发环境下可能出现的问题
- Go语言互斥锁(sync.Mutex)和读写互斥锁(sync.RWMutex)
- Go语言等待组(sync.WaitGroup)
- Go语言死锁、活锁和饥饿概述
- Go语言封装qsort快速排序函数
- Go语言CSP:通信顺序进程简述
- Go语言聊天服务器
- 10.Go语言反射
- Go语言反射(reflection)简述
- Go语言反射规则浅析
- Go语言reflect.TypeOf()和reflect.Type(通过反射获取类型信息)
- Go语言reflect.Elem()——通过反射获取指针指向的元素类型
- Go语言通过反射获取结构体的成员类型
- Go语言结构体标签(Struct Tag)
- Go语言reflect.ValueOf()和reflect.Value(通过反射获取值信息)
- Go语言通过反射访问结构体成员的值
- Go语言IsNil()和IsValid()——判断反射值的空和有效性
- Go语言通过反射修改变量的值
- Go语言通过类型信息创建实例
- Go语言通过反射调用函数
- Go语言inject库:依赖注入
- 11.Go语言网络编程
- Go语言Socket编程详解
- Go语言Dial()函数:建立网络连接
- Go语言ICMP协议:向主机发送消息
- Go语言TCP协议
- Go语言DialTCP():网络通信
- Go语言HTTP客户端实现简述
- Go语言服务端处理HTTP、HTTPS请求
- Go语言RPC协议:远程过程调用
- 如何设计优雅的RPC接口
- Go语言解码未知结构的JSON数据
- Go语言如何搭建网站程序
- Go语言开发一个简单的相册网站
- Go语言数据库(Database)相关操作
- 示例:并发时钟服务器
- Go语言router请求路由
- Go语言middleware:Web中间件
- Go语言常见大型Web项目分层(MVC架构)
- Go语言Cookie的设置与读取
- Go语言获取IP地址和域名解析
- Go语言TCP网络程序设计
- Go语言UDP网络程序设计
- Go语言IP网络程序设计
- Go语言是如何使得Web工作的
- Go语言session的创建和管理
- Go语言Ratelimit服务流量限制
- Go语言WEB框架(Gin)详解
- 12.Go语言文件处理
- Go语言自定义数据文件
- Go语言JSON文件的读写操作
- Go语言XML文件的读写操作
- Go语言使用Gob传输数据
- Go语言纯文本文件的读写操作
- Go语言二进制文件的读写操作
- Go语言自定义二进制文件的读写操作
- Go语言zip归档文件的读写操作
- Go语言tar归档文件的读写操作
- Go语言使用buffer读取文件
- Go语言并发目录遍历
- Go语言从INI配置文件中读取需要的值
- Go语言文件的写入、追加、读取、复制操作
- Go语言文件锁操作
- 13.Go语言网络爬虫
- Go语言网络爬虫概述
- Go语言网络爬虫中的基本数据结构
- Go语言网络爬虫的接口设计
- Go语言网络爬虫缓冲器工具的实现
- Go语言网络爬虫缓冲池工具的实现
- Go语言网络爬虫多重读取器的实现
- Go语言网络爬虫内部基础接口
- Go语言网络爬虫组件注册器
- Go语言网络爬虫下载器接口
- Go语言网络爬虫分析器接口
- Go语言网络爬虫条目处理管道
- Go语言网络爬虫调度器的实现
- Go语言爬取图片小程序
- 14.Go语言编译和工具链
- go build命令(go语言编译命令)完全攻略
- go clean命令——清除编译文件
- go run命令——编译并运行
- go fmt命令——格式化代码文件
- go install命令——编译并安装
- go get命令——一键获取代码、编译并安装
- go generate命令——在编译前自动化生成某类代码
- go test命令(Go语言测试命令)完全攻略
- go pprof命令(Go语言性能分析命令)完全攻略
- 15.Go语言避坑与技巧
- goroutine(Go语言并发)如何使用才更加高效?
- Go语言反射——性能和灵活性的双刃剑
- Go语言接口的nil判断
- Go语言map的多键索引——多个数值条件可以同时查询
- Go语言与C/C++进行交互
- Go语言文件读写
- Json数据编码和解码
- Go语言使用select切换协程
- Go语言加密通信
- Go语言内存管理简述
- Go语言垃圾回收
- Go语言哈希函数
- Go语言分布式id生成器
- 部署Go语言程序到Linux服务器
- Go语言实现RSA和AES加解密
