Pythonで学ぶNLPの特徴量エンジニアリング
Rounak Banik
Data Scientist
"I don't know." # 13 characters
# 文字数を計算
text = "I don't know."
num_char = len(text)
# 文字数を出力
print(num_char)
13
# 'num_chars' 特徴量を作成
df['num_chars'] = df['review'].apply(len)
# 文字列を単語に分割
text = "Mary had a little lamb."
words = text.split()
# 単語のリストを表示
print(words)
['Mary', 'had', 'a', 'little', 'lamb.']
# 単語数を表示
print(len(words))
5
# 文字列中の単語数を返す関数
def word_count(string):
# 文字列を単語に分割
words = string.split()
# 単語リストの長さを返す
return len(words)
# dfにnum_words特徴量を作成
df['num_words'] = df['review'].apply(word_count)
# 平均単語長を返す関数 def avg_word_length(x):# 文字列を単語に分割 words = x.split()# 各単語の長さを計算しリスト化 word_lengths = [len(word) for word in words]# 平均単語長を計算 avg_word_length = sum(word_lengths)/len(words)# 平均単語長を返す return(avg_word_length)
# 新しい特徴量 avg_word_length を作成
df['avg_word_length'] = df['review'].apply(doc_density)

# ハッシュタグ数を返す関数 def hashtag_count(string):# 文字列を単語に分割 words = string.split()# ハッシュタグのリストを作成 hashtags = [word for word in words if word.startswith('#')]# ハッシュタグ数を返す return len(hashtags)
hashtag_count("@janedoe This is my first tweet! #FirstTweet #Happy")
2
Pythonで学ぶNLPの特徴量エンジニアリング