MikiTech

文系新卒エンジニアの学習記録

【Python】言語処理100本ノック2020 03. 円周率

Pythonの勉強も兼ねた言語処理100本ノックです。

問題文

nlp100.github.io

“Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.

コード

import collections

text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
text = text.replace(",", "").replace(".", "")
#単語の文字数カウント
wordNum = [len(word) for word in text.split()]
print(wordNum)


#アルファベットの数カウント
counter = {}
for word in text:
    if not word in counter:
        counter[word] = 1
    else:
        counter[word] += 1

print(counter)

#出力結果
#[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]
#{'N': 1, 'o': 6, 'w': 1, ' ': 14, 'I': 1, 'n': 6, 'e': 9, 'd': 2, 'a': 6, 'r': 4, 'i': 5, 'k': 1, 'l': 4, 'c': 6, 'h': 4, 'f': 2, 'u': 4, 's': 3, 't': 4, 'v': 3, 'y': 1, 'g': 1, 'q': 1, 'm': 2}

なんか急に難しくなかった気が…。
各単語の文字数の部分のコードは以下の通りです。

text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."

#単語の文字数カウント
text = text.replace(",", "").replace(".", "")
wordNum = [len(word) for word in text.split()]
print(wordNum)

replaceメソッドでカンマとピリオドを空白に置き換え、実質的な削除をしました。
そこからsplitメソッドを使い単語の間にある空白で区切っています。
wordという変数に格納して、その長さをそれぞれ出力しています。

#splitのイメージ
text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
print(text.split())

#出力結果
#['Now', 'I', 'need', 'a', 'drink,', 'alcoholic', 'of', 'course,', 'after', 'the', 'heavy', 'lectures', 'involving', 'quantum', 'mechanics.']

splitメソッドについてはコチラを参考にしてました。 note.nkmk.me

Collectionライブラリのcounterメソッドを使うという手もあったようですが、
今回は直接dict型(辞書型)の箱に入れていく形にしていきました。

text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
text = text.replace(",", "").replace(".", "")

#アルファベットの数カウント
counter = {}
for word in text:
    if not word in counter:
        counter[word] = 1
    else:
        counter[word] += 1

print(counter)

#出力結果
#{'N': 1, 'o': 6, 'w': 1, ' ': 14, 'I': 1, 'n': 6, 'e': 9, 'd': 2, 'a': 6, 'r': 4, 'i': 5, 'k': 1, 'l': 4, 'c': 6, 'h': 4, 'f': 2, 'u': 4, 's': 3, 't': 4, 'v': 3, 'y': 1, 'g': 1, 'q': 1, 'm': 2}

変数counterに{}で辞書型のデータを定義します。

counter{}にtextから一文字ずつアルファベットを取り出し、
アルファベットがない場合は、1を設定。
ある場合は(else)、+=1でカウントを増やしていきます。

こうすることでマップ型でアルファベットのカウントができていきます。

単語の文字数カウントも同じように辞書型にすればもう少しキレイな出力ができると思います。

以上になります。
何かあれば教えて下さい!