2016-04-06 18 views
1

私は正規表現の辞書を持っており、複合語を含むトピックと正規表現で辞書内の一致を数えたいと思います。 Python pandas count number of Regex matches in a string:私は質問のようなコードを使用することができます一致をカウントする正規表現と文字列の複合語の一致をカウントするPython pandas

import pandas as pd 


terms = {'animals':"(fox|russian brown deer|bald eagle|arctic fox)", 
'people':'(John Adams|Rob|Steve|Superman|Super man)', 
'games':'(basketball|basket ball|bball)' 
} 

df=pd.DataFrame({ 
'Score': [4,6,2,7,8], 
'Foo': ['Superman was looking for a russian brown deer.', 'John adams started to play basket ball with rob yesterday before steve called him','Basketball or bball is a sport played by Steve afterschool','The bald eagle flew pass the arctic fox three times','The fox was sptted playing basket ball?'] 
}) 

。しかし、文字列を空白で分割し、複合語を含まない用語を数えます。スペースで結ばれた複合語が含まれるようにこれを行う別の方法は何ですか? 3行の北極キツネおよびワード北極キツネのワードキツネは(一緒に2回)各回カウントされるべきであることを

            Foo Score animals people \ 
0  Superman was looking for a russian brown deer.  4  1  1 
1 John adams started to play basket ball with ro...  6  0  3 
2 Basketball or bball is a sport played by Steve...  2  0  1 
3 The bald eagle flew pass the artic fox three t...  7  3  0 
4    The fox was sptted playing basket ball  8  1  0 

    games 
0  0 
1  1 
2  2 
3  0 
4  1 

df1 = df.Foo.str.split(expand=True).stack().reset_index(level=1, drop=True).reset_index(name='Foo') 



for k, v in terms.items(): 
    df1[k] = df1.Foo.str.contains('(?i)(^|\s)'+terms[k]+'($|\s|\.|,|\?)') 


df2= df1.groupby('index').sum().astype(int) 


df = pd.concat([df,df2], axis=1) 
print(df) 

最終結果は次のようになります。動物の柱。

答えて

0

これはあなたが探していたものであるかどうかを確認してください:

import(re) 
for k in terms.keys(): 
    df[k] = 0 
    for words in re.sub("[()]","",terms[k]).split('|'): 
     mask = df.Foo.str.contains(words, case = False) 
     df[k] += mask 
df 


               Foo Score people animals games 
0 Superman was looking for a russian brown deer.  4  1  1  0 
1 John adams started to play basket ball with ro... 6  3  0  1 
2 Basketball or bball is a sport played by Steve... 2  1  0  2 
3 The bald eagle flew pass the arctic fox three ... 7  0  3  0 
4 The fox was sptted playing basket ball?    8  0  1  1 
+0

はい代替の略sub'正規表現ライブラリ – ccsv

+1

'におけるサブ機能に本当に慣れていない感謝を。あなたが最初の用語辞書にカッコを入れると、この 'sub 'は必要ありません –

+0

私はコードのおかげで遊んでそれを考え出しました! – ccsv

関連する問題