Created
April 13, 2014 23:01
-
-
Save brandonrachal/10605780 to your computer and use it in GitHub Desktop.
A Go Lang Program to Convert Special Symbols to HTML Entities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"bufio" | |
"os" | |
"strconv" | |
) | |
func ReadLinesFromFile(file_path string) ([]string, error) { | |
var lines []string | |
src_file, err := os.Open(file_path) | |
if err != nil { panic(err) } | |
defer func() { | |
src_file.Close() | |
}() | |
reader := bufio.NewScanner(src_file) | |
for reader.Scan() { | |
lines = append(lines, LineToHTMLEntities(reader.Text())) | |
} | |
return lines, reader.Err() | |
} | |
func WriteLinesToFile(file_path string, lines []string) error { | |
dst_file, err := os.Create(file_path) | |
if err != nil { panic(err) } | |
defer func() { | |
dst_file.Close() | |
}() | |
writer := bufio.NewWriter(dst_file) | |
for i := 0; i < len(lines); i++ { | |
fmt.Fprintln(writer, lines[i]) | |
} | |
return writer.Flush() | |
} | |
func LineToHTMLEntities(line string) string { | |
var converted string = "" | |
for _, rune_value := range line { | |
converted += RuneToHTMLEntity(rune_value) | |
} | |
return converted | |
} | |
func RuneToHTMLEntity(entity rune) string { | |
if (entity < 128) { | |
return string(entity) | |
} else { | |
return "&#" + strconv.FormatInt(int64(entity), 10) + ";" | |
} | |
} | |
func main() { | |
var srcFile string = "input.txt" | |
var dstFile string = "output.txt" | |
convertedLines, err := ReadLinesFromFile(srcFile) | |
if (err != nil) { fmt.Println(err) } | |
if err := WriteLinesToFile(dstFile, convertedLines); err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment