LoginSignup
3
1

More than 5 years have passed since last update.

素人の言語処理100本ノック:17

Last updated at Posted at 2016-10-02

言語処理100本ノック 2015の挑戦記録です。環境はUbuntu 16.04 LTS + Python 3.5.2 :: Anaconda 4.1.1 (64-bit)です。過去のノックの一覧はこちらからどうぞ。

第2章: UNIXコマンドの基礎

hightemp.txtは,日本の最高気温の記録を「都道府県」「地点」「℃」「日」のタブ区切り形式で格納したファイルである.以下の処理を行うプログラムを作成し,hightemp.txtを入力ファイルとして実行せよ.さらに,同様の処理をUNIXコマンドでも実行し,プログラムの実行結果を確認せよ.

17.1列目の文字列の異なり

1列目の文字列の種類(異なる文字列の集合)を求めよ.確認にはsort, uniqコマンドを用いよ.

出来上がったコード:

main.py
# coding: utf-8

fname = 'hightemp.txt'
with open(fname) as data_file:

    set_ken = set()
    for line in data_file:
        cols = line.split('\t')
        set_ken.add(cols[0])

for n in set_ken:
    print(n)

実行結果:

実行結果1
山形県
和歌山県
岐阜県
大阪府
愛媛県
埼玉県
愛知県
高知県
群馬県
千葉県
山梨県
静岡県
実行結果2
岐阜県
山形県
静岡県
愛知県
大阪府
高知県
群馬県
千葉県
山梨県
愛媛県
和歌山県
埼玉県

2回実行すると並びが変わりました。これは、コマンドラインの-Rオプションの解説にあるように、ハッシュがランダム化されているためだと思います。

UNIXコマンド確認用のシェルスクリプト:

test.sh
#!/bin/sh

# 先頭カラムを切り出し、ソート、重複除去
cut --fields=1 hightemp.txt | sort | uniq > result_test.txt

# Pythonのプログラムで実行、diffで比較するためにソート
python main.py | sort > result.txt

# 結果の確認
diff --report-identical-files result.txt result_test.txt

結果の確認:

端末
segavvy@ubuntu:~/ドキュメント/言語処理100本ノック2015/17$ ./test.sh
ファイル result.txt と result_test.txt は同一です

  
18本目のノックは以上です。誤りなどありましたら、ご指摘いただけますと幸いです。

3
1
2

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