【Python】言語処理100本ノック2020 11. タブをスペースに置換
問題
タブ1文字につきスペース1文字に置換せよ.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ.
環境
Macbook
Python3.7.7
ソースコード
GitHubを載せておきます。
with open('chart2/popular-names.txt','r') as file: for text in file: # タブ(\t)を 空白へ置換(stripで連続する空白を除去) print(text.strip().replace("\t"," ")) #出力イメージ John M 60929 1968 James M 60693 1968 Robert M 58211 1968 William M 36956 1968 Mark M 35420 1968 Richard M 32987 1968 ‥‥
そこまで難しいコードではありませんでした。
openでfileを開いて、stripは合っても無くても大丈夫です。
ポイントはreplaceメソッド。
note.nkmk.me
shellコマンドについては以下の通りです。
sed "s/[[:blank:]]/ /g" chart2/popular-names.txt tr '\t' ' ' chart2/popular-names.txt expand -t 1 chart2/popular-names.txt 出力イメージ John M 60929 1968 James M 60693 1968 Robert M 58211 1968 William M 36956 1968 Mark M 35420 1968 Richard M 32987 1968 ‥‥ 3つほどshellコマンドの書き方があります。 sedとtrとexpandです。 それぞれ詳しい使い方はコチラを見てください。 [https://www.atmarkit.co.jp/ait/articles/1610/17/news015.html#_ga=2.122614539.1254482470.1598443470-1239605920.1588746283:title] [https://www.atmarkit.co.jp/ait/articles/1611/02/news023.html:title] [https://www.atmarkit.co.jp/ait/articles/1610/03/news017.html:title] 以上ですm(_ _)m