言語処理100本ノック
http://www.cl.ecei.tohoku.ac.jp/nlp100/
から第2章 10〜19までを記載
10. 行数のカウント
行数をカウントせよ.確認にはwcコマンドを用いよ.
$ wc -l hightemp.txt
print(len(open('hightemp.txt').readlines()))
11. タブをスペースに置換
タブ1文字につきスペース1文字に置換せよ.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ.
$ sed 's/\t/ /g' hightemp.txt
r = open('hightemp.txt').readlines()
print(''.join([l.replace('\t', ' ') for l in r]))
print(open('hightemp.txt').read().replace('\t', ' '))
12. 1列目をcol1.txtに,2列目をcol2.txtに保存
各行の1列目だけを抜き出したものをcol1.txtに,2列目だけを抜き出したものをcol2.txtとしてファイルに保存せよ.確認にはcutコマンドを用いよ.
$ cut -f 1 hightemp.txt > col1.txt
$ cut -f 2 hightemp.txt > col2.txt
r = open('hightemp.txt').readlines()
with open('col1.txt', 'w') as c1, open('col2.txt', 'w') as c2:
for l in r:
s = l.split('\t')
c1.write(s[0]+'\n')
c2.write(s[1]+'\n')
13. col1.txtとcol2.txtをマージ
12で作ったcol1.txtとcol2.txtを結合し,元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ.確認にはpasteコマンドを用いよ.
$ paste col1.txt col2.txt
c1 = open('col1.txt').readlines()
c2 = open('col2.txt').readlines()
for s1, s2 in zip(c1, c2):
print(s1.rstrip() + '\t' + s2.rstrip())
14. 先頭からN行を出力
自然数Nをコマンドライン引数などの手段で受け取り,入力のうち先頭のN行だけを表示せよ.確認にはheadコマンドを用いよ.
$ head -n 5 hightemp.txt
import sys
n = int(sys.argv[1])
r = open('hightemp.txt').readlines()
print(''.join(r[:n]))
15. 末尾のN行を出力
自然数Nをコマンドライン引数などの手段で受け取り,入力のうち末尾のN行だけを表示せよ.確認にはtailコマンドを用いよ.
$ tail -n 5 hightemp.txt
import sys
n = int(sys.argv[1])
r = open('hightemp.txt').readlines()
print(''.join(r[-n:]))
16. ファイルをN分割する
自然数Nをコマンドライン引数などの手段で受け取り,入力のファイルを行単位でN分割せよ.同様の処理をsplitコマンドで実現せよ.
$ split -l 5 hightemp.txt
import sys
import math
n = int(sys.argv[1])
r = open('hightemp.txt').readlines()
for i in range(n):
l = math.ceil((len(r)+1) / n)
with open('split0' + str(i) + '.txt', 'w') as f:
f.write(''.join(r[l*i:l*i+l-1]))
17. 1列目の文字列の異なり
1列目の文字列の種類(異なる文字列の集合)を求めよ.確認にはsort, uniqコマンドを用いよ.
$ cut -f 1 hightemp.txt | sort | uniq
r = open('hightemp.txt').readlines()
print('\n'.join(set((x.split('\t')[0] for x in r))))
18. 各行を3コラム目の数値の降順にソート
各行を3コラム目の数値の逆順で整列せよ(注意: 各行の内容は変更せずに並び替えよ).確認にはsortコマンドを用いよ(この問題はコマンドで実行した時の結果と合わなくてもよい).
$ sort -r -n -k 3,3 hightemp.txt
r = open('hightemp.txt').readlines()
r.sort(key=lambda x: x.split('\t')[2], reverse=True)
print(''.join(r))
19. 各行の1コラム目の文字列の出現頻度を求め,出現頻度の高い順に並べる
各行の1列目の文字列の出現頻度を求め,その高い順に並べて表示せよ.確認にはcut, uniq, sortコマンドを用いよ
$ cut -f 1 hightemp.txt | sort | uniq -c | sort -r
r = open('hightemp.txt').readlines()
r = list(map(lambda s: s.split()[0], r))
c = {s: r.count(s) for s in r}
c = sorted(c.items(), key=lambda x: x[1], reverse=True)
print('\n'.join(map(lambda s: str(s[1]) + ' ' + s[0], c)))
r = [s.split('\t')[0] for s in open('hightemp.txt')]
c = {k:r.count(k) for k in r}
s = sorted(c, key=lambda k:c[k], reverse=True)
print('\n'.join(str(c[k])+' '+k for k in s))