はじめに
言語処理の問題集として有名な、言語処理100本ノックを実施していこうと思います。
基本的に1章の内容を1投稿または2投稿程度でまとめていこうかと思います。
第1章:準備運動
00. 文字列の逆順
文字列”stressed”の文字を逆に(末尾から先頭に向かって)並べた文字列を得よ.
word1 = "stressed"
def reverse_func(word):
word_list = []
for i in range(len(word1)):
word_list.append(word[i])
reverse_word = ""
for i in range(len(word1)):
reverse_word += word_list.pop()
return reverse_word
print(reverse_func(word1))
>desserts
何となく関数の形で回答を作成しました。
空のリストに文字を順番に足した後に、リストの最後から順に取り出して逆順の文字列を生成しています。
01. 「パタトクカシーー」
「パタトクカシーー」という文字列の1,3,5,7文字目を取り出して連結した文字列を得よ.
word2 = "パタトクカシーー"
def odd_num_word_func(word):
odd_num_word = ""
for i in range(0, len(word), 2):
odd_num_word += word[i]
return odd_num_word
print(odd_num_word_func(word2))
>パトカー
ポイント
range(start, stop, step)
start : インデックスの参照したい最初の値 stop : インデックスの参照したい最後の値+1 step : インデックスを何個おきに参照するか(デフォルトは1)
新しい空の文字列を作成して、forループを用いて文字を追加して生成しています。
02. 「パトカー」+「タクシー」=「パタトクカシーー」
「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.
word3 = "パトカー"
word4 = "タクシー"
def combine_word_func(word1, word2):
combined_word = ""
for i in range(len(word1)):
combined_word = combined_word + word1[i] + word2[i]
return combined_word
print(combine_word_func(word3, word4))
>パタトクカシーー
新しい空の文字列を作成して、forループを回して、各単語から文字を一文字ずつ読み込んで生成しています。
※文字列の長さが異なると機能しません
03. 円周率
“Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
sentence1 = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
def word_length_func(sentence):
sentence = sentence.replace(",", "")
sentence = sentence.replace(".", "")
sentence_list = sentence.split()
cap_num_list = []
for word in sentence_list:
cap_num_list.append(len(word))
return cap_num_list
print(word_length_func(sentence1))
>[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]
まず文章中の不要なカンマとピリオドを取り除いています。
その後、文章をスペースで分割してリスト化。
最後にリスト中の単語をforループで呼び出して、長さを空のリストに追加しています。
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文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
phrase1 = "Hi He Lied Because Boron Could Not Oxideze Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
def element_func(phrase):
phrase = phrase.replace(".", "")
phrase_list = phrase.split()
num = [1, 5, 6, 7, 8, 9, 15, 16, 19]
element_dic = {}
for i in range(len(phrase_list)):
if i + 1 in num:
element_dic[phrase_list[i][:1]] = i + 1
else:
element_dic[phrase_list[i][:2]] = i + 1
return element_dic
print(element_func(phrase1))
>{'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}
まず文章中の不要なピリオドを取り除いています。
その後、文章をスペースで分割してリスト化。
最後にリスト中の単語をforループで呼び出して、何番目の単語によって取得する文字数を変えて空のリストに追加しています。
05以降の問題は次回の投稿に掲載します。