コード例 #1
0
def main():
	datastore.connect()

	data = []

	for doc_id in datastore.get_all_ids(limit=-1):
		row = datastore.get(doc_id, ["id", "content", "meta_info"])

		# Solr へ登録するデータ構造へ変換
		meta_info = json.loads(row["meta_info"])

		data.append({
			"id": str(row["id"]),
			"doc_id_i": row["id"],
			"content_txt_ja": row["content"],
			"title_txt_ja": meta_info["title"],
			"url_s": meta_info["url"]
		})

	# Solr への登録を実行
	indexer.put("doc", data)

	datastore.close()

	return
コード例 #2
0
def main():
    datastore.connect()

    print("Success connecting 'sample.db'")

    # SQLite より id の一覧を取得
    # 1つずつ処理を進める
    for doc_id in datastore.get_all_ids(limit=-1):
        # SQLite より文章を取得
        row = datastore.get(doc_id=doc_id, fl=["content"])
        text = row["content"]

        # 取得した文章を CaboCha で係り受け構造の解析を行い,
        # 文, 文節, 単語に分割されたデータを取得
        sentences, chunks, tokens = parser.parse(text)

        print(f"parsed: doc_id={doc_id}")

        # SQLite に解析結果を保存
        datastore.put_annotation(doc_id, "sentence", sentences)
        datastore.put_annotation(doc_id, "chunk", chunks)
        datastore.put_annotation(doc_id, "token", tokens)

    datastore.close()

    return
コード例 #3
0
def main():
	datastore.connect()

	sentences = []

	# :TODO 書籍と異なる方法で記載. 後ほど変更する
	# **** ここから ****
	for doc_id, in datastore.get_all_ids(limit=20):
		for sentence in datastore.get_annotation(doc_id, "sentence"):
			tokens = find_xs_in_y(
				datastore.get_annotation(doc_id, "token"),
				sentence
			)

			sentences.append((doc_id, sentence, tokens))
	# **** ここまで ****

	rule = ruleclassifier.get_rule()

	# 分類
	feature = ruleclassifier.convert_into_feature_using_rules(sentences, rule)

	predict = ruleclassifier.classify(feature, rule)

	for predicted, (doc_id, sentence, tokens) in zip(predict, sentences):
		if predicted == 1:
			text = datastore.get(doc_id, ["content"])["content"]

			print(predicted, text[sentence["begin"]: sentence["end"]])

	datastore.close()

	return
コード例 #4
0
def main():
	datastore.connect()

	values = []

	for file in glob.glob("./../data/html/*.html"):
		with open(file, encoding="utf-8") as f:
			html = f.read()

			text, title = scrape.scrape(html)

			url = f"http://ja.wikipedia.org/wiki/{urllib.parse.quote(title)}"

			value = (
				text,
				json.dumps({"url": url, "title": title}, ensure_ascii=False)
			)

			values.append(value)

			print(f"scrape: {title}")

	datastore.put(values)

	print(list(datastore.get_all_ids(limit=-1)))

	datastore.close()

	return
コード例 #5
0
def main():
    datastore.connect()

    for doc_id in datastore.get_all_ids(limit=10):
        row = datastore.get(doc_id, ["id", "content", "meta_info"])

        print(f"{row['id']}\n"
              f"{row['meta_info']}\n"
              f"{row['content']}\n"
              f"********")

    datastore.close()

    return
コード例 #6
0
def main():
    datastore.connect()

    # SQLite より id の一覧を取得
    # 1つずつ処理を進める
    for doc_id in datastore.get_all_ids(limit=-1):
        # SQLite より文章を取得
        row = datastore.get(doc_id=doc_id, fl=["content"])
        text = row["content"]

        # token を取得し, それらを出力
        print("token:")

        tokens = datastore.get_annotation(doc_id, "token")

        for token in tokens:
            print(
                f"    {token['POS']}    {text[token['begin']: token['end']]}")

        # chunk を取得し, それらを出力
        print("chunks:")

        chunks = datastore.get_annotation(doc_id, "chunk")

        for chunk in chunks:
            _, link = chunk["link"]
            print(f"    {text[chunk['begin']: chunk['end']]}")

            if link != -1:
                parent = chunks[link]
                print(f"     --> {text[parent['begin']: parent['end']]}")
            else:
                print(f"     --> {None}")

        print("sentences:")

        sentences = datastore.get_annotation(doc_id, "sentence")

        for sentence in sentences:
            print(f"     --> {text[sentence['begin']: sentence['end']]}")

    datastore.close()

    return
コード例 #7
0
def main():
    # SQLite に接続
    datastore.connect()

    data = []
    doc_ids = []

    # doc_id を 1つずつ取得し, それに含まれている単語の原形を取得
    for doc_id in datastore.get_all_ids(limit=-1):
        lemmas = [
            token["lemma"]
            for token in datastore.get_annotation(doc_id, "token")
        ]

        data.append(" ".join(lemmas))
        doc_ids.append(doc_id)

    # TF-IDF を算出
    vectorizer = TfidfVectorizer(analyzer="word", max_df=0.9)
    vectors = vectorizer.fit_transform(data)

    # doc_id ごとに TF-IDF の値が高い単語を表示
    # まずは, doc_id に紐づく meta データを取得
    for doc_id, vec in zip(doc_ids, vectors.toarray()):
        # meta データから doc_id に紐づく title を取得
        meta_info = json.loads(
            datastore.get(doc_id, ["meta_info"])["meta_info"])

        title = meta_info["title"]

        print(doc_id, title)

        # TF-IDF を出力
        for w_id, tf_idf in sorted(enumerate(vec),
                                   key=lambda x: x[1],
                                   reverse=True)[:10]:
            lemma = vectorizer.get_feature_names()[w_id]

            print(f"\t{lemma}: {tf_idf}")

    datastore.close()

    return
コード例 #8
0
def main():
	# SQLite に接続
	datastore.connect()

	data = []
	doc_ids = []

	# doc_id を 1つずつ取得し, それに含まれている単語の原形を取得
	for doc_id in datastore.get_all_ids(limit=-1):
		lemmas = [
			token["lemma"]
			for token in datastore.get_annotation(doc_id, "token")
		]

		data.append(" ".join(lemmas))
		doc_ids.append(doc_id)

	# TF-IDF を算出
	vectorizer = TfidfVectorizer(analyzer="word", max_df=0.9)
	vectors = vectorizer.fit_transform(data)

	# コサイン類似度を算出
	sim = cosine_similarity(vectors)

	# doc_id と, それに対するコサイン類似度の算出結果を紐づけ
	docs = zip(doc_ids, sim[0])

	# doc_id ごとに コサイン類似度にもとづく類似度の高い文書を表示
	# まずは, doc_id に紐づく meta データを取得
	for doc_id, similarity in sorted(docs, key=lambda x: x[1], reverse=True):
		meta_info = json.loads(
			datastore.get(doc_id, ["meta_info"])["meta_info"]
		)

		title = meta_info["title"]

		# doc_id とコサイン類似度にもとづく類似度の高い文書, その値を出力
		print(doc_id, title, similarity)

	datastore.close()

	return
コード例 #9
0
def main():
    # SQLite に接続
    datastore.connect()

    annotation_name = "affiliation"

    # 全てのレコードを取得し, 1レコードずつ, 格納されているアノテーションを出力
    for doc_id in datastore.get_all_ids(limit=-1):
        row = datastore.get(doc_id=doc_id, fl=["content"])
        text = row["content"]

        annotations = datastore.get_annotation(doc_id, annotation_name)

        for annotation in annotations:
            print(
                f"{annotation_name.upper()}: {text[annotation['begin']: annotation['end']]}"
            )

    datastore.close()

    return
コード例 #10
0
def main() -> None:
    datastore.connect()

    # - SQLite より全ての doc_id を取得
    # - doc_id に対応する文書を取得
    # - 正規表現を用いて, 関係性を抽出
    for doc_id in datastore.get_all_ids(limit=-1):
        text = datastore.get(doc_id, fl=["content"])["content"]

        for sentence, relation in extract_relation(doc_id):
            print(f"文書: {doc_id}	{text[sentence['begin']: sentence['end']]}")

            for annotation_name, annotation in relation.items():
                print(
                    f"{annotation_name}	{text[annotation['begin']: annotation['end']]}"
                )

            print("\n ******** \n")

    datastore.close()

    return
コード例 #11
0
def main():
    # SQLite に接続
    datastore.connect()

    # 言語モデルを作成
    lm = statistics.create_language_model(datastore.get_all_ids(limit=-1), n=3)

    text = "古くから人が居住する。"

    sentences, chunks, tokens = parser.parse(text)

    probabilities = set([])

    for i in range(1000):
        tokens_ = tokens[1:]

        random.shuffle(tokens_)

        tokens_shuffle = [tokens[0]] + tokens_

        lemmas = ["__BOS__"] + [token["lemma"]
                                for token in tokens_shuffle] + ["__EOS__"]

        shuffled_text = "".join(
            [text[token["begin"]:token["end"]] for token in tokens_shuffle])

        probability = statistics.calc_prob(lm, lemmas, n=3)
        probabilities.add((probability, shuffled_text))

    for probability, shuffled_text in sorted(list(probabilities),
                                             reverse=True)[:20]:
        print(f"{probability}: {shuffled_text}")

    datastore.close()

    return
コード例 #12
0
def main():
    # SQLite に接続
    datastore.connect()

    # 言語モデルを作成
    lm = statistics.create_language_model(datastore.get_all_ids(limit=-1), n=3)

    context = ("古く", "から")
    print(f"{context} =>")

    # 言語モデルを作成し, context の次に出現する単語の一覧と, そのスコアを取得
    prob_list = [(word, lm.score(word, context))
                 for word in lm.context_counts(lm.vocab.lookup(context))]

    # 単語の一覧をスコアが高い順番に sort
    prob_list.sort(key=lambda x: x[1], reverse=True)

    # 単語の一覧を出力
    for word, prob in prob_list:
        print(f"{word.ljust(8)}: {prob}")

    datastore.close()

    return
コード例 #13
0
def main():
	client = datastore.connect()

	# アノテーションを格納するための column を作成(該当するテーブルがない場合のみ, 作成)
	columns = [i[1] for i in client.execute(f"PRAGMA table_info(docs)")]

	new_columns = [
		"cause",
		"effect"
	]

	for new_column in new_columns:
		if new_column not in columns:
			client.execute(
				f"ALTER TABLE docs ADD COLUMN '{new_column}' 'BLOB'"
			)

			client.commit()

			print(f"Create new column: {new_column}")

		else:
			print(f"Already exist table column: {new_column}")

	# - SQLite より全ての doc_id を取得
	# - doc_id に対応する文書を取得
	# - 正規表現を用いて, 関係性を抽出
	for doc_id in datastore.get_all_ids(limit=-1):
		text = datastore.get(doc_id, fl=["content"])["content"]

		annotations = {}

		for sentence, relation in extract_relation(doc_id):
			print(f"文書	{doc_id}	{text[sentence['begin']: sentence['end']]}")

			for annotation_name, annotation in relation.items():
				print(f"{annotation_name}	{text[annotation['begin']: annotation['end']]}\n")

				annotations.setdefault(annotation_name, []).append(annotation)

		for annotation_name, annotation in annotations.items():
			datastore.put_annotation(doc_id, annotation_name, annotation)

	datastore.close()

	return
コード例 #14
0
def main():
	# 抽出する際に, 指定する正規表現のパターンを作成
	pattern = [
		r".+?大学",
		r".+?学会",
		r".+?協会",
	]

	pattern = re.compile(r"|".join(pattern))

	annotation_name = "affiliation"

	# SQLite に接続
	client = datastore.connect()

	# アノテーションを格納するための column を作成(該当するテーブルがない場合のみ, 作成)
	columns = [i[1] for i in client.execute(f"PRAGMA table_info(docs)")]

	if annotation_name not in columns:
		client.execute(
			f"ALTER TABLE docs ADD COLUMN '{annotation_name}' 'BLOB'"
		)

		client.commit()

		print(f"Create new column: {annotation_name}")

	else:
		print(f"Already exist table column: {annotation_name}")

	# SQLite より 1レコードずつ取得し, アノテーションを付与
	# その後, それらを SQLite に格納する
	for doc_id in datastore.get_all_ids(limit=-1):
		annotations = create_annotation(doc_id, pattern)

		datastore.put_annotation(doc_id, annotation_name, annotations)

	datastore.close()

	return
コード例 #15
0
def main():
    datastore.connect()
    datastore.create_table()
    datastore.close()

    return
コード例 #16
0
def main():
    # SQLite に接続
    datastore.connect()

    # dic_id を1つずつ取得し, その doc_id 内の文章ごとに含まれる単語の原形を sentences に格納
    sentences = []

    for doc_id in datastore.get_all_ids(limit=-1):
        all_tokens = datastore.get_annotation(doc_id, "token")

        for sentence in datastore.get_annotation(doc_id, "sentence"):
            tokens = find_xs_in_y(all_tokens, sentence)

            sentences.append(
                [token["lemma"] for token in tokens if token.get("NE") == "O"])

    # 分析に使用する記事が少ないため, 20文を 1つの文書として扱うように sentence を結合
    n_sent = 20

    docs = [
        list(itertools.chain.from_iterable(sentences[i:i + n_sent]))
        for i in range(0, len(sentences), n_sent)
    ]

    # LDA の計算に使用する単語を選定
    # - 出現頻度が 2つ未満の文書の場合, その単語は計算に使用しない( no_below=2 )
    # - 出現頻度が 3割以上の文書の場合, その単語は計算に使用しない( no_above=0.3 )
    dictionary = Dictionary(docs)
    dictionary.filter_extremes(no_below=2, no_above=0.3)

    # 単語の集まりを doc2bow method を用いて, 所定のデータ型に変換
    corpus = [dictionary.doc2bow(doc) for doc in docs]

    # LDA モデルを作成
    lda = LdaModel(corpus, num_topics=10, id2word=dictionary, passes=10)

    # 主題の確認
    # Topic の一覧を出力
    # Topic の一覧と合わせて, その Topic の中で確率値の大きい単語上位 10個を出力
    for topic in lda.show_topics(num_topics=-1, num_words=10):
        print(f"Topic id: {topic[0]}    Word: {topic[1]}")

    # 記事の主題分布の推定
    # doc_id ごとに確率値の大きい Topic を出力
    for doc_id in datastore.get_all_ids(limit=-1):
        meta_info = json.loads(
            datastore.get(doc_id=doc_id, fl=["meta_info"])["meta_info"])

        title = meta_info["title"]
        print(title)

        doc = [
            token["lemma"]
            for token in datastore.get_annotation(doc_id, "token")
            if token.get("NE") == "O"
        ]

        topics = sorted(lda.get_document_topics(dictionary.doc2bow(doc)),
                        key=lambda x: x[1],
                        reverse=True)

        for topic in topics:
            print(f"    Topic id: {topic[0]}    Prob: {topic[1]}")

    datastore.close()

    return