我有一個文本 A 和一個文本 B。我希望找到文本 B 中的單詞百分比(計算所有出現次數)不存在于文本 A 的詞匯表(即所有唯一單詞的串列)中。
例如,
A = "一只貓和一只貓和一只老鼠"
B = “一只肥貓,還有更多的貓和更多的老鼠”
B有12個字。Plump, some, more, mice and too 不在 A 中。 Plumb 不在 A 中,出現一次,有些出現兩次,更多兩次,老鼠一次,也出現一次。B 中的 12 個單詞中有 7 個不在 A 中。--> 58 % 的 B 不在 A 中。
我認為我們可以使用 Tensorflow 的 Tokenizer。我們可能還可以使用其他東西,普通的 python 或其他標記器和其他解決方案是受歡迎的。
使用 tf.Tokenizer 我得到word_index文本 A
a_tokenizer = Tokenizer()
a_tokenizer.fit_on_texts(textA) #Builds the word index
word_index=a_tokenizer.word_index
和word_count文本 B
b_tokenizer = Tokenizer()
b_tokenizer.fit_on_texts(generated_text)
word_count=b_tokenizer.word_count
實作這一目標的一個壞方法是遍歷 B 中的單詞word_count并在 A 中查找
num_words_b=0
num_words_b_in_a=0
for word_b, count_b in tokenizer.word_count.items():
num_words_b = count_b
for word_a, index_a in tokenizer.word_index.items():
if word_b == word_a:
num_words_b_in_a = count_b
breaks
然后做1-num_words_b_in_a/num_words_b。一些更優雅的查找?
編輯:實際上上面根本不起作用,因為它標記為字符。我想將其標記為文字。
uj5u.com熱心網友回復:
也許嘗試這樣的事情:
import tensorflow as tf
docs1 = ['Well done!',
'Good work',
'Great effort',
'nice work',
'Excellent!']
docs2 = ['Well!',
'work',
'work',
'effort',
'rabbit',
'nice']
a = tf.keras.preprocessing.text.Tokenizer()
a.fit_on_texts(docs1)
b = tf.keras.preprocessing.text.Tokenizer()
b.fit_on_texts(docs2)
word_index = a.word_index
word_counts = dict(b.word_counts)
diff = set(word_counts.keys()).intersection(set(word_index.keys()))
num_words_b = sum(list(word_counts.values()))
num_words_b_in_a = sum(list(map(word_counts.get, list(diff))))
percentage = 1 - num_words_b_in_a/ num_words_b
print(percentage)
0.16666666666666663
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/432304.html
