東北大学 乾・岡崎研究室のWebページにて公開されている「自然言語処理100本ノック 2015」を解いていこうと思うので、その記録としてまとめる。
00. 文字列の逆順
文字列"stressed"の文字を逆に(末尾から先頭に向かって)並べた文字列を得よ.
指定された文字列を逆順で表示すれば良い。
キーワードは「Extended Slices」。
# -*- coding: utf-8 -*-
__author__ = 'todoroki'
string = "stressed"
print string[::-1]
#=> desserts
ポイントは [::-1]
。
文字列の反転を取得するときはこう書けばいいと覚えておくのもありだと思う。
どうしてこうなるかは、python公式ドキュメントの該当部分を見るとわかるけど、ここでは説明を割愛する。
01. 「パタトクカシーー」
「パタトクカシーー」という文字列の1,3,5,7文字目を取り出して連結した文字列を得よ.
これも「Extended Slices」で解ける。
# -*- coding: utf-8 -*-
__author__ = 'todoroki'
string = u"パタトクカシーー"
print string[::2]
#=> パトカー
文字列の先頭から末尾まで2文字刻みでスライスして表示している。
02. 「パトカー」+「タクシー」=「パタトクカシーー」
「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.
この問題は「zip」関数を利用する。
# -*- coding: utf-8 -*-
__author__ = 'todoroki'
string1 = u"パトカー"
string2 = u"タクシー"
ans = u""
for a, b in zip(string1, string2):
ans += a + b
print ans
#=> パタトクカシーー
zip関数はそれぞれのシーケンスのi番目の要素をタプルとして返す関数であるので、zip関数を利用することで2つのシーケンスオブジェクトを並行して扱うことができる。
03. 円周率
"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
# -*- coding: utf-8 -*-
__author__ = 'todoroki'
string = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.'
ans = []
for s in string.split():
s = s.replace(",", "").replace(".", "")
ans.append(len(s))
print ans
#=> [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]
指定した文字で対象をスライスする split()
メソッドを利用。
何も指定しない場合は空白区切りが適用される。
,
や .
が邪魔なので置換してから文字数を数える。
04. 元素記号
"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
# -*- coding: utf-8 -*-
__author__ = 'todoroki'
string = 'Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'
index = [1, 5, 6, 7, 8, 9, 15, 16, 19]
ans = {}
for i, s in enumerate(string.split(), 1):
if i in index:
ans[s[0]] = i
else:
ans[s[0:2]] = i
print ans
#=> {'Be': 4, 'C': 6, 'B': 5, 'Ca': 20, 'F': 9, 'S': 16, 'H': 1, 'K': 19, 'Al': 13, 'Mi': 12, 'Ne': 10, 'O': 8, 'Li': 3, 'P': 15, 'Si': 14, 'Ar': 18, 'Na': 11, 'N': 7, 'Cl': 17, 'He': 2}
指定された単語に関してはスライスで2文字取り出す。
enumerate関数の第2引数を指定することでカウンタの開始値を指定可能(python2.6からの機能らしい[参照])。