2022-08-04 06:59:33 +00:00
<!DOCTYPE HTML>
< html lang = "zh" class = "sidebar-visible no-js light" >
< head >
<!-- Book generated using mdBook -->
< meta charset = "UTF-8" >
< title > 查找重复的行 - Go语言圣经< / title >
<!-- Custom HTML head -->
< meta content = "text/html; charset=utf-8" http-equiv = "Content-Type" >
< meta name = "description" content = "<The Go Programming Language>中文版" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< meta name = "theme-color" content = "#ffffff" / >
< link rel = "icon" href = "../favicon.svg" >
< link rel = "shortcut icon" href = "../favicon.png" >
< link rel = "stylesheet" href = "../css/variables.css" >
< link rel = "stylesheet" href = "../css/general.css" >
< link rel = "stylesheet" href = "../css/chrome.css" >
< link rel = "stylesheet" href = "../css/print.css" media = "print" >
<!-- Fonts -->
< link rel = "stylesheet" href = "../FontAwesome/css/font-awesome.css" >
< link rel = "stylesheet" href = "../fonts/fonts.css" >
<!-- Highlight.js Stylesheets -->
< link rel = "stylesheet" href = "../highlight.css" >
< link rel = "stylesheet" href = "../tomorrow-night.css" >
< link rel = "stylesheet" href = "../ayu-highlight.css" >
<!-- Custom theme stylesheets -->
< link rel = "stylesheet" href = "../style.css" >
< / head >
< body >
<!-- Provide site root to javascript -->
< script type = "text/javascript" >
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
< / script >
<!-- Work around some values being stored in localStorage wrapped in quotes -->
< script type = "text/javascript" >
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') & & theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') & & sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
< / script >
<!-- Set the theme before any content is loaded, prevents flash -->
< script type = "text/javascript" >
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
< / script >
<!-- Hide / unhide sidebar before it is displayed -->
< script type = "text/javascript" >
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
< / script >
< nav id = "sidebar" class = "sidebar" aria-label = "Table of contents" >
< div class = "sidebar-scrollbox" >
2023-06-26 17:30:52 +00:00
< ol class = "chapter" > < li class = "chapter-item expanded affix " > < a href = "../index.html" > Go语言圣经< / a > < / li > < li class = "chapter-item expanded affix " > < a href = "../preface-zh.html" > 译者序< / a > < / li > < li class = "chapter-item expanded affix " > < a href = "../preface.html" > 前言< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch1/ch1.html" > < strong aria-hidden = "true" > 1.< / strong > 入门< / a > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../ch1/ch1-01.html" > < strong aria-hidden = "true" > 1.1.< / strong > Hello, World< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch1/ch1-02.html" > < strong aria-hidden = "true" > 1.2.< / strong > 命令行参数< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch1/ch1-03.html" class = "active" > < strong aria-hidden = "true" > 1.3.< / strong > 查找重复的行< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch1/ch1-04.html" > < strong aria-hidden = "true" > 1.4.< / strong > GIF动画< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch1/ch1-05.html" > < strong aria-hidden = "true" > 1.5.< / strong > 获取URL< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch1/ch1-06.html" > < strong aria-hidden = "true" > 1.6.< / strong > 并发获取多个URL< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch1/ch1-07.html" > < strong aria-hidden = "true" > 1.7.< / strong > Web服务< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch1/ch1-08.html" > < strong aria-hidden = "true" > 1.8.< / strong > 本章要点< / a > < / li > < / ol > < / li > < li class = "chapter-item expanded " > < a href = "../ch2/ch2.html" > < strong aria-hidden = "true" > 2.< / strong > 程序结构< / a > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../ch2/ch2-01.html" > < strong aria-hidden = "true" > 2.1.< / strong > 命名< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch2/ch2-02.html" > < strong aria-hidden = "true" > 2.2.< / strong > 声明< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch2/ch2-03.html" > < strong aria-hidden = "true" > 2.3.< / strong > 变量< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch2/ch2-04.html" > < strong aria-hidden = "true" > 2.4.< / strong > 赋值< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch2/ch2-05.html" > < strong aria-hidden = "true" > 2.5.< / strong > 类型< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch2/ch2-06.html" > < strong aria-hidden = "true" > 2.6.< / strong > 包和文件< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch2/ch2-07.html" > < strong aria-hidden = "true" > 2.7.< / strong > 作用域< / a > < / li > < / ol > < / li > < li class = "chapter-item expanded " > < a href = "../ch3/ch3.html" > < strong aria-hidden = "true" > 3.< / strong > 基础数据类型< / a > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../ch3/ch3-01.html" > < strong aria-hidden = "true" > 3.1.< / strong > 整型< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch3/ch3-02.html" > < strong aria-hidden = "true" > 3.2.< / strong > 浮点数< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch3/ch3-03.html" > < strong aria-hidden = "true" > 3.3.< / strong > 复数< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch3/ch3-04.html" > < strong aria-hidden = "true" > 3.4.< / strong > 布尔型< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch3/ch3-05.html" > < strong aria-hidden = "true" > 3.5.< / strong > 字符串< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch3/ch3-06.html" > < strong aria-hidden = "true" > 3.6.< / strong > 常量< / a > < / li > < / ol > < / li > < li class = "chapter-item expanded " > < a href = "../ch4/ch4.html" > < strong aria-hidden = "true" > 4.< / strong > 复合数据类型< / a > < / li > < li > < ol class = "section" > < li class = "chapter-item expanded " > < a href = "../ch4/ch4-01.html" > < strong aria-hidden = "true" > 4.1.< / strong > 数组< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch4/ch4-02.html" > < strong aria-hidden = "true" > 4.2.< / strong > Slice< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch4/ch4-03.html" > < strong aria-hidden = "true" > 4.3.< / strong > Map< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch4/ch4-04.html" > < strong aria-hidden = "true" > 4.4.< / strong > 结构体< / a > < / li > < li class = "chapter-item expanded " > < a href = "../ch4/ch4-05.html" > < strong aria-hidden = "true" > 4.5.<
2022-08-04 06:59:33 +00:00
< div id = "sidebar-resize-handle" class = "sidebar-resize-handle" > < / div >
< / nav >
< div id = "page-wrapper" class = "page-wrapper" >
< div class = "page" >
< div id = "menu-bar-hover-placeholder" > < / div >
< div id = "menu-bar" class = "menu-bar sticky bordered" >
< div class = "left-buttons" >
< button id = "sidebar-toggle" class = "icon-button" type = "button" title = "Toggle Table of Contents" aria-label = "Toggle Table of Contents" aria-controls = "sidebar" >
< i class = "fa fa-bars" > < / i >
< / button >
< button id = "theme-toggle" class = "icon-button" type = "button" title = "Change theme" aria-label = "Change theme" aria-haspopup = "true" aria-expanded = "false" aria-controls = "theme-list" >
< i class = "fa fa-paint-brush" > < / i >
< / button >
< ul id = "theme-list" class = "theme-popup" aria-label = "Themes" role = "menu" >
< li role = "none" > < button role = "menuitem" class = "theme" id = "light" > Light (default)< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "rust" > Rust< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "coal" > Coal< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "navy" > Navy< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "ayu" > Ayu< / button > < / li >
< / ul >
< button id = "search-toggle" class = "icon-button" type = "button" title = "Search. (Shortkey: s)" aria-label = "Toggle Searchbar" aria-expanded = "false" aria-keyshortcuts = "S" aria-controls = "searchbar" >
< i class = "fa fa-search" > < / i >
< / button >
< / div >
< h1 class = "menu-title" > Go语言圣经< / h1 >
< div class = "right-buttons" >
< a href = "../print.html" title = "Print this book" aria-label = "Print this book" >
< i id = "print-button" class = "fa fa-print" > < / i >
< / a >
< a href = "https://github.com/gopl-zh/gopl-zh.github.com" title = "Git repository" aria-label = "Git repository" >
< i id = "git-repository-button" class = "fa fa-github" > < / i >
< / a >
< a href = "https://github.com/gopl-zh/gopl-zh.github.com/edit/master/./ch1/ch1-03.md" title = "Suggest an edit" aria-label = "Suggest an edit" >
< i id = "git-edit-button" class = "fa fa-edit" > < / i >
< / a >
< / div >
< / div >
< div id = "search-wrapper" class = "hidden" >
< form id = "searchbar-outer" class = "searchbar-outer" >
< input type = "search" id = "searchbar" name = "searchbar" placeholder = "Search this book ..." aria-controls = "searchresults-outer" aria-describedby = "searchresults-header" >
< / form >
< div id = "searchresults-outer" class = "searchresults-outer hidden" >
< div id = "searchresults-header" class = "searchresults-header" > < / div >
< ul id = "searchresults" >
< / ul >
< / div >
< / div >
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
< script type = "text/javascript" >
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
< / script >
< div id = "content" class = "content" >
<!-- Page table of contents -->
< div class = "sidetoc" > < nav class = "pagetoc" > < / nav > < / div >
< main >
<!-- 头部 -->
< ul dir = "auto" >
2024-06-12 07:20:07 +00:00
< li > < em > Go语言圣经读书笔记(挖坑中...): < a href = "https://github.com/chai2010/gopl-notes-zh" > https://github.com/chai2010/gopl-notes-zh< / a > < / em > < / li >
< li > < em > 凹语言(Go实现, 面向WASM设计): < a href = "https://github.com/wa-lang/wa" > https://github.com/wa-lang/wa< / a > < / em > < / li >
2023-06-26 17:46:27 +00:00
< / ul >
2022-08-04 06:59:33 +00:00
< hr >
< h2 id = "13-查找重复的行" > < a class = "header" href = "#13-查找重复的行" > 1.3. 查找重复的行< / a > < / h2 >
2022-08-09 12:23:16 +00:00
< p > 对文件做拷贝、打印、搜索、排序、统计或类似事情的程序都有一个差不多的程序结构:一个处理输入的循环,在每个元素上执行计算处理,在处理的同时或最后产生输出。我们会展示一个名为 < code > dup< / code > 的程序的三个版本;灵感来自于 Unix 的 < code > uniq< / code > 命令,其寻找相邻的重复行。该程序使用的结构和包是个参考范例,可以方便地修改。< / p >
< p > < code > dup< / code > 的第一个版本打印标准输入中多次出现的行,以重复次数开头。该程序将引入 < code > if< / code > 语句,< code > map< / code > 数据类型以及 < code > bufio< / code > 包。< / p >
2022-08-04 06:59:33 +00:00
< p > < u > < i > gopl.io/ch1/dup1< / i > < / u > < / p >
< pre > < code class = "language-go" > // Dup1 prints the text of each line that appears more than
// once in the standard input, preceded by its count.
package main
import (
" bufio"
" fmt"
" os"
)
func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
counts[input.Text()]++
}
// NOTE: ignoring potential errors from input.Err()
for line, n := range counts {
if n > 1 {
fmt.Printf(" %d\t%s\n" , n, line)
}
}
}
< / code > < / pre >
2022-08-09 12:23:16 +00:00
< p > 正如 < code > for< / code > 循环一样,< code > if< / code > 语句条件两边也不加括号,但是主体部分需要加。< code > if< / code > 语句的 < code > else< / code > 部分是可选的,在 < code > if< / code > 的条件为 < code > false< / code > 时执行。< / p >
< p > < strong > map< / strong > 存储了键/值( key/value) 的集合, 对集合元素, 提供常数时间的存、取或测试操作。键可以是任意类型, 只要其值能用 < code > ==< / code > 运算符比较,最常见的例子是字符串;值则可以是任意类型。这个例子中的键是字符串,值是整数。内置函数 < code > make< / code > 创建空 < code > map< / code > , 此外, 它还有别的作用。4.3 节讨论 < code > map< / code > 。< / p >
< p > (译注:从功能和实现上说,< code > Go< / code > 的 < code > map< / code > 类似于 < code > Java< / code > 语言中的 < code > HashMap< / code > , Python 语言中的 < code > dict< / code > , < code > Lua< / code > 语言中的 < code > table< / code > ,通常使用 < code > hash< / code > 实现。遗憾的是,对于该词的翻译并不统一,数学界术语为< em > 映射< / em > ,而计算机界众说纷纭莫衷一是。为了防止对读者造成误解,保留不译。)< / p >
< p > 每次 < code > dup< / code > 读取一行输入,该行被当做键存入 < code > map< / code > ,其对应的值递增。< code > counts[input.Text()]++< / code > 语句等价下面两句:< / p >
2022-08-04 06:59:33 +00:00
< pre > < code class = "language-go" > line := input.Text()
counts[line] = counts[line] + 1
< / code > < / pre >
2022-08-09 12:23:16 +00:00
< p > < code > map< / code > 中不含某个键时不用担心,首次读到新行时,等号右边的表达式 < code > counts[line]< / code > 的值将被计算为其类型的零值,对于 < code > int< / code > 即 < code > 0< / code > 。< / p >
< p > 为了打印结果,我们使用了基于 < code > range< / code > 的循环,并在 < code > counts< / code > 这个 < code > map< / code > 上迭代。跟之前类似,每次迭代得到两个结果,键和其在 < code > map< / code > 中对应的值。< code > map< / code > 的迭代顺序并不确定,从实践来看,该顺序随机,每次运行都会变化。这种设计是有意为之的,因为能防止程序依赖特定遍历顺序,而这是无法保证的。(译注:具体可以参见这里< a href = "https://stackoverflow.com/questions/11853396/google-go-lang-assignment-order" > https://stackoverflow.com/questions/11853396/google-go-lang-assignment-order< / a > ) < / p >
< p > 继续来看 < code > bufio< / code > 包,它使处理输入和输出方便又高效。< code > Scanner< / code > 类型是该包最有用的特性之一,它读取输入并将其拆成行或单词;通常是处理行形式的输入最简单的方法。< / p >
< p > 程序使用短变量声明创建 < code > bufio.Scanner< / code > 类型的变量 < code > input< / code > 。< / p >
< pre > < code class = "language-go" > input := bufio.NewScanner(os.Stdin)
2022-08-04 06:59:33 +00:00
< / code > < / pre >
2022-08-09 12:23:16 +00:00
< p > 该变量从程序的标准输入中读取内容。每次调用 < code > input.Scan()< / code > ,即读入下一行,并移除行末的换行符;读取的内容可以调用 < code > input.Text()< / code > 得到。< code > Scan< / code > 函数在读到一行时返回 < code > true< / code > ,不再有输入时返回 < code > false< / code > 。< / p >
< p > 类似于 C 或其它语言里的 < code > printf< / code > 函数,< code > fmt.Printf< / code > 函数对一些表达式产生格式化输出。该函数的首个参数是个格式字符串, 指定后续参数被如何格式化。各个参数的格式取决于“转换字符”( conversion character) , 形式为百分号后跟一个字母。举个例子, < code > %d< / code > 表示以十进制形式打印一个整型操作数,而 < code > %s< / code > 则表示把字符串型操作数的值展开。< / p >
< p > < code > Printf< / code > 有一大堆这种转换, Go程序员称之为< em > 动词( verb) < / em > 。下面的表格虽然远不是完整的规范,但展示了可用的很多特性:< / p >
< pre > < code class = "language-text" > %d 十进制整数
2022-08-04 06:59:33 +00:00
%x, %o, %b 十六进制,八进制,二进制整数。
%f, %g, %e 浮点数: 3.141593 3.141592653589793 3.141593e+00
%t 布尔: true或false
%c 字符( rune) (Unicode码点)
%s 字符串
%q 带双引号的字符串" abc" 或带单引号的字符'c'
%v 变量的自然形式( natural format)
%T 变量的类型
%% 字面上的百分号标志(无操作数)
< / code > < / pre >
2022-08-09 12:23:16 +00:00
< p > < code > dup1< / code > 的格式字符串中还含有制表符< code > \t< / code > 和换行符< code > \n< / code > 。字符串字面上可能含有这些代表不可见字符的< strong > 转义字符( escape sequences) < / strong > 。默认情况下,< code > Printf< / code > 不会换行。按照惯例,以字母 < code > f< / code > 结尾的格式化函数,如 < code > log.Printf< / code > 和 < code > fmt.Errorf< / code > ,都采用 < code > fmt.Printf< / code > 的格式化准则。而以 < code > ln< / code > 结尾的格式化函数,则遵循 < code > Println< / code > 的方式,以跟 < code > %v< / code > 差不多的方式格式化参数,并在最后添加一个换行符。(译注:后缀 < code > f< / code > 指 < code > format< / code > , < code > ln< / code > 指 < code > line< / code > 。)< / p >
< p > 很多程序要么从标准输入中读取数据,如上面的例子所示,要么从一系列具名文件中读取数据。< code > dup< / code > 程序的下个版本读取标准输入或是使用 < code > os.Open< / code > 打开各个具名文件,并操作它们。< / p >
2022-08-04 06:59:33 +00:00
< p > < u > < i > gopl.io/ch1/dup2< / i > < / u > < / p >
< pre > < code class = "language-go" > // Dup2 prints the count and text of lines that appear more than once
// in the input. It reads from stdin or from a list of named files.
package main
import (
" bufio"
" fmt"
" os"
)
func main() {
counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, " dup2: %v\n" , err)
continue
}
countLines(f, counts)
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf(" %d\t%s\n" , n, line)
}
}
}
func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
// NOTE: ignoring potential errors from input.Err()
}
< / code > < / pre >
2022-08-09 12:23:16 +00:00
< p > < code > os.Open< / code > 函数返回两个值。第一个值是被打开的文件(< code > *os.File< / code > ),其后被 < code > Scanner< / code > 读取。< / p >
< p > < code > os.Open< / code > 返回的第二个值是内置 < code > error< / code > 类型的值。如果 < code > err< / code > 等于内置值< code > nil< / code > (译注:相当于其它语言里的 < code > NULL< / code > ),那么文件被成功打开。读取文件,直到文件结束,然后调用 < code > Close< / code > 关闭该文件,并释放占用的所有资源。相反的话,如果 < code > err< / code > 的值不是 < code > nil< / code > ,说明打开文件时出错了。这种情况下,错误值描述了所遇到的问题。我们的错误处理非常简单,只是使用 < code > Fprintf< / code > 与表示任意类型默认格式值的动词 < code > %v< / code > ,向标准错误流打印一条信息,然后 < code > dup< / code > 继续处理下一个文件;< code > continue< / code > 语句直接跳到 < code > for< / code > 循环的下个迭代开始执行。< / p >
< p > 为了使示例代码保持合理的大小,本书开始的一些示例有意简化了错误处理,显而易见的是,应该检查 < code > os.Open< / code > 返回的错误值,然而,使用 < code > input.Scan< / code > 读取文件过程中, 不大可能出现错误, 因此我们忽略了错误处理。我们会在跳过错误检查的地方做说明。5.4 节中深入介绍错误处理。< / p >
< p > 注意 < code > countLines< / code > 函数在其声明前被调用。函数和包级别的变量( package-level entities) 可以任意顺序声明, 并不影响其被调用。( 译注: 最好还是遵循一定的规范) < / p >
< p > < code > map< / code > 是一个由 < code > make< / code > 函数创建的数据结构的引用。< code > map< / code > 作为参数传递给某函数时, 该函数接收这个引用的一份拷贝( copy, 或译为副本) , 被调用函数对 < code > map< / code > 底层数据结构的任何修改,调用者函数都可以通过持有的 < code > map< / code > 引用看到。在我们的例子中,< code > countLines< / code > 函数向 < code > counts< / code > 插入的值,也会被 < code > main< / code > 函数看到。(译注:类似于 C++ 里的引用传递,实际上指针是另一个指针了,但内部存的值指向同一块内存)< / p >
< p > < code > dup< / code > 的前两个版本以" 流”模式读取输入,并根据需要拆分成多个行。理论上,这些程序可以处理任意数量的输入数据。还有另一个方法,就是一口气把全部输入数据读到内存中,一次分割为多行,然后处理它们。下面这个版本,< code > dup3< / code > ,就是这么操作的。这个例子引入了 < code > ReadFile< / code > 函数(来自于< code > io/ioutil< / code > 包),其读取指定文件的全部内容,< code > strings.Split< / code > 函数把字符串分割成子串的切片。(< code > Split< / code > 的作用与前文提到的 < code > strings.Join< / code > 相反。)< / p >
< p > 我们略微简化了 < code > dup3< / code > 。首先,由于 < code > ReadFile< / code > 函数需要文件名作为参数,因此只读指定文件,不读标准输入。其次,由于行计数代码只在一处用到,故将其移回 < code > main< / code > 函数。< / p >
2022-08-04 06:59:33 +00:00
< p > < u > < i > gopl.io/ch1/dup3< / i > < / u > < / p >
< pre > < code class = "language-go" > package main
import (
" fmt"
" io/ioutil"
" os"
" strings"
)
func main() {
counts := make(map[string]int)
for _, filename := range os.Args[1:] {
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, " dup3: %v\n" , err)
continue
}
for _, line := range strings.Split(string(data), " \n" ) {
counts[line]++
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf(" %d\t%s\n" , n, line)
}
}
}
< / code > < / pre >
2022-08-09 12:23:16 +00:00
< p > < code > ReadFile< / code > 函数返回一个字节切片( byte slice) , 必须把它转换为 < code > string< / code > ,才能用 < code > strings.Split< / code > 分割。我们会在3.5.4 节详细讲解字符串和字节切片。< / p >
< p > 实现上,< code > bufio.Scanner< / code > 、< code > ioutil.ReadFile< / code > 和 < code > ioutil.WriteFile< / code > 都使用 < code > *os.File< / code > 的 < code > Read< / code > 和 < code > Write< / code > 方法, 但是, 大多数程序员很少需要直接调用那些低级( lower-level) 函数。高级( higher-level) 函数, 像 < code > bufio< / code > 和 < code > io/ioutil< / code > 包中所提供的那些,用起来要容易点。< / p >
< hr / >
< p > < strong > 练习 1.4: < / strong > 修改 < code > dup2< / code > ,出现重复的行时打印文件名称。< / p >
2022-08-04 06:59:33 +00:00
<!-- 公众号 -->
< hr >
< table >
< tr >
< td >
< img width = "222px" src = "https://chai2010.cn/advanced-go-programming-book/css.png" >
< / td >
< td >
< img width = "222px" src = "https://chai2010.cn/advanced-go-programming-book/cch.png" >
< / td >
< / tr >
< / table >
< div id = "giscus-container" > < / div >
< footer class = "page-footer" >
< span > © 2015-2016 | < a href = "https://github.com/gopl-zh" > Go语言圣经中文版< / a > , 仅学习交流使用< / span >
< / footer >
< / main >
< nav class = "nav-wrapper" aria-label = "Page navigation" >
<!-- Mobile navigation buttons -->
< a rel = "prev" href = "../ch1/ch1-02.html" class = "mobile-nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
< i class = "fa fa-angle-left" > < / i >
< / a >
< a rel = "next" href = "../ch1/ch1-04.html" class = "mobile-nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
< i class = "fa fa-angle-right" > < / i >
< / a >
< div style = "clear: both" > < / div >
< / nav >
< / div >
< / div >
< nav class = "nav-wide-wrapper" aria-label = "Page navigation" >
< a rel = "prev" href = "../ch1/ch1-02.html" class = "nav-chapters previous" title = "Previous chapter" aria-label = "Previous chapter" aria-keyshortcuts = "Left" >
< i class = "fa fa-angle-left" > < / i >
< / a >
< a rel = "next" href = "../ch1/ch1-04.html" class = "nav-chapters next" title = "Next chapter" aria-label = "Next chapter" aria-keyshortcuts = "Right" >
< i class = "fa fa-angle-right" > < / i >
< / a >
< / nav >
< / div >
< script type = "text/javascript" >
window.playground_copyable = true;
< / script >
< script src = "../elasticlunr.min.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../mark.min.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../searcher.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../clipboard.min.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../highlight.js" type = "text/javascript" charset = "utf-8" > < / script >
< script src = "../book.js" type = "text/javascript" charset = "utf-8" > < / script >
< script type = "text/javascript" charset = "utf-8" >
var pagePath = "ch1/ch1-03.md"
< / script >
<!-- Custom JS scripts -->
< script type = "text/javascript" src = "../js/custom.js" > < / script >
< script type = "text/javascript" src = "../js/bigPicture.js" > < / script >
< / body >
< / html >