背景
言語処理100本ノック 2015を今やっているのでその備忘録的なやつ。
やりたいこと
Pythonで"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."という文章を単語に分解して各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成する。
結果
文章を単語ごとに分割して分割した単語の文字数をfor文でリスト内にinsertして対応しました。
import re sentense = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.' splited = re.split('\s', sentense.replace('.', '')) cntlist = [] for i in range (0, len(splited)): cntlist.insert(i, len(splited[i])) splited > [3, 1, 4, 1, 6, 9, 2, 7, 5, 3, 5, 8, 9, 7, 9]
解説/考察
Pythonの標準ライブラリのreを使用しました。
6.2. re — 正規表現操作 — Python 3.6.1 ドキュメント
reを使用して単語を分割するとコンマが残ってしまったのでreplaceを使用してピリオドを文章内から抹消しています。他にも方法あるんですかね?
> sentense = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.' > sentense.replace('.', '') > 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics'
reのsplit関数を使用して文章を分割しました。
今回は任意の空白文字とマッチする部分で分けたいのでpatternに\sを指定してます。
\W+でも問題ないっぽいです。
正規表現はここにまとまっています。
正規表現 HOWTO — Python 3.6.1 ドキュメント
> import re > sentense = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.' > re.split('\s', sentense.replace('.', '')) > ['Now', 'I', 'need', 'a', 'drink,', 'alcoholic', 'of', 'course,', 'after', 'the', 'heavy', 'lectures', 'involving', 'quantum', 'mechanics']
文章を単語ごとに分解できたので、分割した単語数分for文でリストにデータを流し込む作業をしています。
# 空のリストを用意 cntlist = [] # len(splited)で分割した単語数を取得して値を渡してあげる for i in range (0, len(splited)): #リストのi番目に分割したi番目の単語の文字数をinsertする cntlist.insert(i, len(splited[i]))
以上!