pythonで二つの文字列を比較してマッチ率を算出する
説明
二つの英語の文章を比較して、どのくらいマッチした単語があるかを調べます。その時、二文字以下の英単語は端折ることにします。まず、英文章のテキストから二文字以上の英単語を一個づつ取り出して配列にアップエンドして配列を作ります。そのあとに、作った二つの配列の中から重複した値のみを取り出して、その数を取ります。最後に、比較元の配列の数と、重複して取り出した値の数を比較します。計算式はx=重複した文字の数÷比較元の配列の数×100です。
実装
# -*- coding: utf-8 -*-
# ライブラリの読み込み
import re
from collections import Counter
#
#
#
#
# 1個目の処理
#
#
#
#
target_text = """
Why are you always so energetic? Where does that smile come from? I do not understand. Your way is really kind.
"""
words = re.split(r'\s|\,|\.|\(|\)', target_text.lower())
counter = Counter(words)
myList=[]
num=0
for word, count in counter.most_common():
if len(word) > 2:
myList.append( "%s" % (word) )
#
#
#
#
# 2個目の処理
#
#
#
#
result_text = """
he is so strong My heart has gone somewhere. I am thinking how I should get along with you. Because I am very weak.
"""
result_words = re.split(r'\s|\,|\.|\(|\)', result_text.lower())
result_counter = Counter(result_words)
result_myList=[]
for word, count in result_counter.most_common():
if len(word) > 2:
result_myList.append( "%s" % (word) )
result_juuhuku=list( set(myList) & set(result_myList) )
kextuka = float( len(result_juuhuku) ) / len(result_myList) * 100
#
#
#
#
# デバック確認
#
#
#
#
print( "リファレンスファイルの単語配列" )
print( result_myList )
print( "ターゲットの単語配列" )
print( myList )
print( "重複した値" )
print( list( set(myList) & set(result_myList) ) )
print( "マッチした比率は" )
print(round(kextuka, 2))
実行
$ /usr/bin/python polyglot.py
リファレンスファイルの単語配列
['heart', 'because', 'gone', 'somewhere', 'should', 'how', 'you', 'has', 'get', 'very', 'weak', 'along', 'strong', 'with', 'thinking']
ターゲットの単語配列
['are', 'your', 'really', 'does', 'way', 'smile', 'you', 'that', 'energetic?', 'understand', 'not', 'from?', 'come', 'why', 'kind', 'always', 'where']
重複した値
['you']
マッチした比率は
6.67