LoginSignup
5
13

More than 5 years have passed since last update.

Python100本ノック(5/100)

Last updated at Posted at 2018-02-13

はじめに

Pythonを行き当たりばったりで触ってきたので
何処までPythonできているのかを見つめ直すために、自然言語処理100本ノックしていきます。
python2ばっかり使っていましたので、慣れるためにpython3でやっていきます。


00. 文字列の逆順

    text = u'stressed'
    print(text[::-1])
desserts

01. [パタトクカシーー]

text = u'パタトクカシーー'
print(text[::2])
パトカー

02. [パトカー]+[タクシー]=[パタトクカシーー]

a = u'パトカー'
b = u'タクシー'
text = u''
for i, j in zip(a, b):
    text += i + j
print(text)
パタトクカシーー

forにしてしまったけど、joinと内包表記使った方がよかったらしい。
print(''.join([i + j for i, j in zip(a, b)]))
内包表記は多様しますが、さらに関数に渡すことはあまりしてこなかったのでこの発想にいたりませんでした。

03. 円周率

text = u'Now I need a drink, alcoholic of course, after the heavy lectures inbolving quantum mechanics.'
words = [sorted(w.strip(',.'), key=lambda x: w.count(x), reverse=True)
         for w in text.split()]
print(words)
[['N', 'o', 'w'], ['I'], ['e', 'e', 'n', 'd'], ['a'], ['d', 'r', 'i', 'n', 'k'], ['l', 'c', 'o', 'o', 'l', 'c', 'a', 'h', 'i'], ['o', 'f'], ['c', 'o', 'u', 'r', 's', 'e'], ['a', 'f', 't', 'e', 'r'], ['t', 'h', 'e'], ['h', 'e', 'a', 'v', 'y'], ['e', 'e', 'l', 'c', 't', 'u', 'r', 's'], ['i', 'n', 'i', 'n', 'b', 'o', 'l', 'v', 'g'], ['u', 'u', 'q', 'a', 'n', 't', 'm'], ['c', 'c', 'm', 'e', 'h', 'a', 'n', 'i', 's']]

splitとstripで英文を単語に分解しました。
その後、悩みましたが、sortedで並び変えを行いました。
そして、他の人の解答を見て問題を読み違えていることに気がつきました!
lenでええやん……
しかも、単語の出現数順にソートしているつもりだったんですが、できてない。

lenにしました。

text = u'Now I need a drink, alcoholic of course, after the heavy lectures inbolving quantum mechanics.'
words = [len(w.strip(',.')) for w in text.split()]
print(words)
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

04. 元素記号

text = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
words = [w.strip(',.') for w in text.split()]
# print(words)
one = [1, 5, 6, 7, 8, 9, 15, 16, 19]
word_dict = {w[0] if words.index(w) + 1 in one else w[:2]: words.index(w)
            for w in words}
print(word_dict)
{'H': 0, 'He': 1, 'Li': 2, 'Be': 3, 'B': 4, 'C': 5, 'N': 6, 'O': 7, 'F': 8, 'Ne': 9, 'Na': 10, 'Mi': 11, 'Al': 12, 'Si': 13, 'P': 14, 'S': 15, 'Cl': 16, 'Ar': 17, 'K': 18, 'Ca': 19}

04と同じく分解しました。
その後、内包表記で辞書を作りました。
辞書に入れる順番が0になっているのは、問題がちゃんと読めていないためです。

一日何問解いていけるかなっという感じでしたが、単語にも疎いため時間がかかりそうです。
次のn-gramってなんだ…?


風呂でのプログラムは、誘惑が少くていい感じです!
問題は湯が冷めてきたら、どうしたらいいかわかんない所。
風呂蓋で多少マシになった気がする。

5
13
0

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
5
13