例えば以下の様な文章があったとする。毎回読む度に元気をくれるアホな話なのでこいつを選んでみました(笑)
My friend ripped open a handwarmer, and when the powder got on his hands his parents told him his hands would disintegrate by age 30. We looked up what disintegrate meant later that night, and he bawled hysterically while staring at his hands.
「この文章をスペースごとに区切ってdictionary
に入れたい」なんてことがこの先あるかもしれません。いや、ないかもしれません。今回はそのやり方についてたまたまSOFで見つけたので勉強のメモがてら使ってみたいと思います。こちらの都合上、関数にまとめてから使うことにします。
s2 = s2 = "My friend ripped open a handwarmer, and when the powder got on his hands his parents told him his hands would disintegrate by age 30. We looked up what disintegrate meant later that night, and he bawled hysterically while staring at his hands"
def splitter(some_sentence):
out = some_sentence.split() # split s by whitespace into out in a form of a list
entries = dict([(x,y) for x,y in zip(out[::2], out[1::2])]) # loops through every word in a given sentence 1st word = key, 2nd word = value
return entries
>>> splitter(s2)
{'that': 'night,', 'My': 'friend', 'a': 'handwarmer,', 'looked': 'up', 'told': 'him', 'what': 'disintegrate', 'and': 'he', 'by': 'age', 'bawled': 'hysterically', 'while': 'staring', 'got': 'on', '30.': 'We', 'the': 'powder', 'at': 'his', 'his': 'hands', 'would': 'disintegrate', 'meant': 'later', 'ripped': 'open'}
個人的にはリストスライシングの使い方に刺激を受けました。リストスライシングってどこにでも応用が効く素晴らしいメソッドだなと。
簡単に役割を説明すると
- まず適当に入れてきた文章を
split
でスペース毎にスライスしてout
に入れる。(リストで)['My', 'friend', 'ripped', 'open', 'a', 'handwarmer,', 'and', 'when', 'the', 'powder', 'got', 'on', 'his', 'hands', 'his', 'parents', 'told', 'him', 'his', 'hands', 'would', 'disintegrate', 'by', 'age', '30.', 'We', 'looked', 'up', 'what', 'disintegrate', 'meant', 'later', 'that', 'night,', 'and', 'he', 'bawled', 'hysterically', 'while', 'staring', 'at', 'his', 'hands']
- そのリストを
out[::2]
とout[1::2]
で分けて前者をx
後者をy
とする。言い方を変えればリストの中の一番最初から一個飛ばしで単語を選んでいく方がx
。飛ばした単語を拾っていくのがy
みたいなイメージ。 -
zip
でx
とy
をタプルの中に入れてペアにする。`[('My', 'friend'), ('ripped', 'open'), ('a', 'handwarmer,'), ('and', 'when'), ('the', 'powder'), ('got', 'on'), ('his', 'hands'), ('his', 'parents'), ('told', 'him'), ('his', 'hands'), ('would', 'disintegrate'), ('by', 'age'), ('30.', 'We'), ('looked', 'up'), ('what', 'disintegrate'), ('meant', 'later'), ('that', 'night,'), ('and', 'he'), ('bawled', 'hysterically'), ('while', 'staring'), ('at', 'his')] -
x
をkey
に。y
をvalue
に入れてdict()
でペアをくっつけて完成。
サイト上の例を構造分解するとこんな感じ:
# s = '#one cat #two dogs #three birds'
# >>> splitter(s)
# out = ['#one', 'cat', '#two', 'dogs', '#three', 'birds']
# out[::2]
# ['#one', '#two', '#three']
# out[1::2]
# ['cat', 'dogs', 'birds']
しかしこんな使い方は絶対しないと思うのでdictionary comprehensionの中にif
を入れて取捨選択してその単語のみを入れるとしたほうが明らかに賢いと思います。もしくはenumerator的な関数をつくってkey
を思いきって番号にするのも有りだと思います。それなら単語の数に応じてkey
の番号が出てくるのでデータの扱いなどで大活躍しそうです。参考までに。
def enumerate(s, start=0):
return zip([i for i in range(start, (start + len(s)))], s)