テキストデータの行列操作で次の問題が発生します。
元のテキストドキュメントもリストに保存しています。以下は、テキストデータのリストの最初の要素の例です。
text_data[1]
u"\n The Bechtel Group Inc. offered in 1985 to sell oil to Israel at a
discount of at least 650 million for 10 years if it promised not to
bomb a proposed Iraqi pipeline, a Foreign Ministry official said
Wednesday. But then-Prime Minister Shimon Peres said the offer from
Bruce Rappaport, a partner in the San Francisco-based construction and
engineering company, was ``unimportant,'' the senior official told The
Associated Press. Peres, now foreign minister, never discussed the
offer with other government ministers, said the official, who spoke on
condition of anonymity.
x_ {ij}がi番目のドキュメントのj番目に配置された単語のterm-indexを示す行列を取得したいと思います。例は次のとおりです。
Words W = np.array([0, 1, 2, 3, 4]) # word indices for a dictionary of words
# D := document words X = np.array([
[0, 0, 1, 2, 2], # e.g., this row means 1st, and 2nd position is the first term in the dictionary, etc.
[0, 0, 1, 1, 1],
[0, 1, 2, 2, 2],
[4, 4, 4, 4, 4],
[3, 3, 4, 4, 4],
[3, 4, 4, 4, 4]
])
私が考えることができるのは、最初にコーパス内の用語の辞書を作成し、それに対応するインデックスを作成することです。次に、各ドキュメントを調べ、ドキュメント全体を繰り返し処理し、ドキュメントiと位置jに表示される単語の用語インデックスを配置します。しかし、これは非常に長く非効率的なようです。
私は数ヶ月前に同様の課題に遭遇しました。PythonNLTKを使用してそれを行う方法があると確信しています。「コーパスからタームカウントベクトル」をグーグルで検索すると、良いスタートを切ることができます。
あなたがあなたの質問で示唆しているように、私はただ自分自身を実装することになりました。
def document_to_term_counts(document, vocab):
term_count = [0] * len(vocab)
for word in document:
if word in vocab:
term_count[vocab.index(word)] += 1
return term_count
def count_words_in_documents(documents):
word_counts = {}
for document in documents:
words_found_in_document = set()
for word in document:
if word not in word_counts:
word_counts[word] = {'all_appearances': 1, 'document_appearances': 1}
else:
word_counts[word]['all_appearances'] += 1
if word not in words_found_in_document:
word_counts[word]['document_appearances'] += 1
words_found_in_document.add(word)
return word_counts
def word_counts_to_vocab(word_counts, min_document_apperances, max_document_apperances):
vocab = []
for word in word_counts:
document_apperances = word_counts[word]['document_appearances']
if document_apperances >= min_document_apperances and document_apperances <= max_document_apperances:
vocab.append(word)
return vocab
def documents_to_vocab(documents, min_document_apperances, max_document_apperances):
word_counts = count_words_in_documents(documents)
vocab = word_counts_to_vocab(word_counts, min_document_apperances, max_document_apperances)
return vocab
documents = [
['the', 'quick', 'brown', 'fox', 'jumped'],
['foxes', 'are', 'quick']
]
vocab = documents_to_vocab(documents, 1, 100)
print('vocabulary:')
print(vocab)
for document in documents:
term_counts = document_to_term_counts(document, vocab)
print('-'*50)
print(document)
print(term_counts)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加