3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

11. タブをスペースに置換

Posted at

11. タブをスペースに置換

タブ1文字につきスペース1文字に置換せよ.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ.

###Go

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	//	読み込みファイルを指定
	name := "../hightemp.txt"

	//	読み込むファイルを開く
	f, err := os.Open(name)
	if err != nil {
		fmt.Printf("os.Open: %#v\n",err)
		return
	}
	defer f.Close() //	終了時にクリーズ

	//	スキャナライブラリを作成
	scanner := bufio.NewScanner(f)

	//	データを1行読み込み
	for scanner.Scan() {
		//	TAB を 空白へ置換
		fmt.Println(strings.Replace(scanner.Text(),"\t"," ",-1))
	}

	//	エラーが有ったかチェック
	if err = scanner.Err(); err != nil {
		fmt.Printf("scanner.Err: %#v\n",err)
		return
	}
}

###python

# ファイルを開く
with open("../hightemp.txt", "r") as f:
    # 一行ずつ読み込む
    for data in f:
        # TAB を 空白へ置換(strip で white space を除去)
        print(data.strip().replace("\t"," "))

###Javascript

// モジュールの読み込み
var fs = require("fs");
var readline = require("readline");

//  ストリームを作成
var stream = fs.createReadStream("../hightemp.txt", "utf8");

//  readlineにStreamを渡す
var reader = readline.createInterface({ input: stream });

//  行読み込みコールバック
reader.on("line", (data) => {
    //  TAB を 空白へ変換(文字列 "\t" 指定ではうまく動作しないため正規表現で指定)
    console.log(data.replace(/\t/g," "))
});

まとめ

Javascirpt で置換元文字列に "\t" が指定出来ないのか?。
Python コード数の少なさに改めて驚く。

トップ

3
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?