LoginSignup
1
1

More than 5 years have passed since last update.

言語処理100本ノック03

Posted at

はじめに

言語処理100本ノックの元サイトのリンク
http://www.cl.ecei.tohoku.ac.jp/nlp100/#data

今回は、あちこちぶつかりながらもなんとか調べて、目的のリストを出力するところまで行きました。

03 円周率

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

03knock.py
from collections import Counter
st="Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."

words=st.replace(",","").replace(".","").split()

list=[]

for i in words:
    k=len(i)
    list.append(k)
print (list)

出力結果
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

最初に躓いたのはスペースで区切る方法。調べるとすぐ出てきました
https://qiita.com/como1559/items/abfcd4f0ce2f611d5193
次に、','と'.'をどうするか悩みなしたが、どうもreplaceとsplit関数は
.replace().split()
と重ねることができるみたいです
http://python-remrin.hatenadiary.jp/entry/2017/04/24/174405

次に躓いたのがlist.append()。最初自分は
list=list.append()
としていましたが
'NoneType' object has no attribute 'append'
とエラーが出てしまう...どうもappend関数は値を返すのではなくて書き換えるみたいです
http://sphdien.hatenablog.com/entry/2013/12/05/181031

最後に躓いたのがfor文の分岐
文字変数を分岐に使えるとは...知らなんだ

1
1
4

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
1
1