LoginSignup
3
0

More than 3 years have passed since last update.

言語処理100本ノック(4本目)

Posted at

撃沈した続き

100本ノックの4本目で何これ怖いってなった続きを書いていきます

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文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.

番号を振る

knock4.py
moji = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
temp= moji.split(" ")

for (i, x) in enumerate(temp,1):
    print(i, x)

splitでスペース区切りで配列に分けた後、1番目から列挙していくためenumerateで(temp,1)のように1,2...と番号を振っていきます

実行結果
1 Hi
2 He
3 Lied
4 Because
5 Boron
6 Could
7 Not
8 Oxidize
9 Fluorine.
10 New
11 Nations
12 Might
13 Also
14 Sign
15 Peace
16 Security
17 Clause.
18 Arthur
19 King
20 Can.

リストを作る

次にリストに文字を入れていきます

knoc4.py
moji = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
temp1= moji.split(" ")

list = {}

for (i, x) in enumerate(temp1 ,1):
    list[x[:]] = i

print(list)
実行結果
{'Hi': 1, 'He': 2, 'Lied': 3, 'Because': 4, 'Boron': 5, 'Could': 6, 'Not': 7, 'Oxidize': 8, 'Fluorine.': 9, 'New': 10, 'Nations': 11, 'Might': 12, 'Also': 13, 'Sign': 14, 'Peace': 15, 'Security': 16, 'Clause.': 17, 'Arthur': 18, 'King': 19, 'Can.': 20}

文字を切り取る

最後に文字を切り取ります。1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は1文字、それ以外は2文字なのでif文で処理を分けていきます

knoc4.py
moji = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
temp1= moji.split(" ")
first_num = (1, 5, 6, 7, 8, 9, 15, 16, 19)

list = {}

for (i, x) in enumerate(temp1 ,1):
    if i in first_num:
        list[x[:1]] = i
    else:
        list[x[:2]] = i

print(list)
実行結果
{'H': 1, 'He': 2, 'Li': 3, 'Be': 4, 'B': 5, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Ne': 10, 'Na': 11, 'Mi': 12, 'Al': 13, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17, 'Ar': 18, 'K': 19, 'Ca': 20}

できました。
問題を最初見たとき何じゃこりゃってなりましたが、少しずつ切り分けて解いていくと良いのかなと思いました。

次回は5問目をやっていこうと思います。どれどれどんな問題……

05. n-gram

与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ.

………えぬぐらむって何ですか?(無知グラマー)

では次回orz

参考サイト

note.nkmk.me
HEADBOOST
鎖プログラム

3
0
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
3
0