言語処理100本ノック 第1章 03 文の各単語の長さを求める Python 複数の文字の置換 スペースで区切る mapでlen

nlp100.github.io

import re

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

# ',' と '.' を削除する
s_sub = re.sub('[,.]', '', s)
print(s_sub)

# スペースで区切って、単語のリストを得る
s_split = s_sub.split()
print(s_split)

# 各単語の長さのリストを得る
len_list = list(map(len, s_split))
print(len_list)
$ python3 03.py 
Now I need a drink alcoholic of course after the heavy lectures involving quantum mechanics
['Now', 'I', 'need', 'a', 'drink', 'alcoholic', 'of', 'course', 'after', 'the', 'heavy', 'lectures', 'involving', 'quantum', 'mechanics']
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]