エントリーから実際の戦闘エンティティのネーミング認識へのNLPエントリー+中国の前処理、従来の簡単な変換、ピンインの取得

中国の伝統的で単純化された変換とピンイン取得の前処理

日常の中国語NLPでは、繁体字中国語から簡体字中国語への変換とピンインのラベル付けが頻繁に行われますが、この記事では、これら2つの側面の実現について紹介します。
 1つ目は、繁体字中国語から簡体字中国語への変換です。追加のPythonモジュールは必要ありません。次の2つのPythonコードファイルが必要です。

サンプルコードは次のとおりです(コードファイルをlangconv.pyおよびzh_wiki.pyと同じディレクトリに配置します)。

from langconv import *

# 转换繁体到简体
def cht_2_chs(line):
    line = Converter('zh-hans').convert(line)
    line.encode('utf-8')
    return line

line_cht= '''
台北市長柯文哲今在臉書開直播,先向網友報告自己3月16日至24日要出訪美國東部4城市,接著他無預警宣布,
2月23日要先出訪以色列,預計停留4至5天。雖他強調台北市、以色列已在資安方面有所交流,也可到當地城市交流、
參觀產業創新等內容,但柯也說「也是去看看一個小國在這麼惡劣環境,howtosurvive,他的祕訣是什麼?」這番話,
也被解讀,頗有更上層樓、直指總統大位的思維。
'''

line_cht = line_cht.replace('\n', '')
ret_chs = cht_2_chs(line_cht)
print(ret_chs)

# 转换简体到繁体
def chs_2_cht(sentence):
    sentence = Converter('zh-hant').convert(sentence)
    return sentence

line_chs = '忧郁的台湾乌龟台北市長柯文哲今在臉書開直播,先向網友報告自己3月16日至24日要出訪美國東部4城市,接著他無預警宣布,'
line_cht = chs_2_cht(line_chs)
print(line_cht)

from xpinyin import Pinyin

p = Pinyin()

# 默认分隔符为-
print(p.get_pinyin("上海"))

# 显示声调
print(p.get_pinyin("上海", tone_marks='marks'))
print(p.get_pinyin("上海", tone_marks='numbers'))

# 去掉分隔符
print(p.get_pinyin("上海", ''))
# 设为分隔符为空格
print(p.get_pinyin("上海", ' '))

# 获取拼音首字母
print(p.get_initial("上"))
print(p.get_initials("上海"))
print(p.get_initials("上海", ''))
print(p.get_initials("上海", ' '))

出力結果は次のとおりです。

台北市のKe Wenzhe市長は本日Facebookで生放送を開始しました。彼は最初に3月16日から24日まで米国東部の4つの都市を訪問するとネチズンに報告しました。その後2月23日に最初にイスラエルを訪問することを警告せずに発表し、4〜5年滞在すると予想されています。日。また、台北市とイスラエルは情報セキュリティに関する情報交換を行っており、地方都市に行って交流したり、産業革新を行ったりすることもできると強調したが、「また、このような過酷な環境で小さな国を見に行った。HowtoSurive、彼の秘密その秘密は何ですか?」これらの言葉も解釈され、大統領を直接指すより高いレベルの思考を持っています。

憂鬱な台湾亀

ここに画像の説明を挿入

次に、漢字のピンインを取得します。この領域のPythonモジュールには、xpinyin、pypinyinなどが含まれますこの記事では、中国語のピンインを取得する方法を示す例としてxpinyinを取り上げます。サンプルコードは次のとおりです。

from xpinyin import Pinyin

p = Pinyin()

# 默认分隔符为-
print(p.get_pinyin("上海"))

# 显示声调
print(p.get_pinyin("上海", tone_marks='marks'))
print(p.get_pinyin("上海", tone_marks='numbers'))

# 去掉分隔符
print(p.get_pinyin("上海", ''))
# 设为分隔符为空格
print(p.get_pinyin("上海", ' '))

# 获取拼音首字母
print(p.get_initial("上"))
print(p.get_initials("上海"))
print(p.get_initials("上海", ''))
print(p.get_initials("上海", ' '))

出力は次のとおりです。

shang-hai
shàng-hǎi
shang4-hai3
shanghai
shang hai
S
S-H
SH
S H

2. NLP Named Entity Recognition(NER)の概要

この記事では、自然言語処理(NLP)における名前付きエンティティ認識(NER)について簡単に紹介します。
 Named Entity Recognition(NER)は、情報抽出、質問応答システム、構文分析、機械翻訳などのアプリケーション分野における重要な基本ツールであり、自然言語処理技術の実用的なプロセスにおいて重要な位置を占めています。一般的に言えば、名前付きエンティティ認識のタスクは、処理されるテキスト内の3つのカテゴリ(エンティティ、時間、および数)と7つのカテゴリ(個人、組織、場所、時間、日付、通貨、およびパーセンテージ)を識別することです。エンティティ。
 簡単な例として、「小明は午前8時に学校に行きます」という文では、名前付きエンティティの認識で情報を抽出できるはずです。

名前:小明、時間:午前8時、場所:学校。

この記事では、名前付きエンティティの認識のためのいくつかのツールを紹介します。将来機会がある場合は、HMM、CRF、またはディープラーニングを使用して、名前付きエンティティの認識を実現してみます。
 まず、以下に示すように、NLTKとスタンフォードNLPでの名前付きエンティティ認識の分類を見てみましょう。

img

NLTKおよびStanford NLPにおける固有表現認識の分類

上の図では、LOCATIONとGPEが重複しています。GPEは通常、都市、州、国、大陸などの地政学的なアイテムを意味します。上記のコンテンツに加えて、LOCATIONは有名な山や川を表すこともできます。FACILITYは通常、有名なモニュメントまたはアーティファクトを意味します。
 NERタスクを実行する2つのツール、NLTKとスタンフォードNLPを次に示します。
 1つ目はNLTKです。サンプルドキュメント(WikipediaのFIFAの紹介)は次のとおりです。

FIFAは1904年に設立され、ベルギー、
デンマーク、フランス、ドイツ、オランダ、スペイン、スウェーデン、スイスの各国協会間の国際競争を監督しています。チューリッヒに本社を置き、その
会員は現在、211の全国協会で構成されています。加盟国はそれぞれ
、世界が分割されている6つの地域連合の1つであるアフリカ、アジア、ヨーロッパ、北中米
とカリブ海、オセアニア、南アメリカのメンバーでなければなりません

NERを実装するPythonコードは次のとおりです。

import re
import pandas as pd
import nltk

def parse_document(document):
   document = re.sub('\n', ' ', document)
   if isinstance(document, str):
       document = document
   else:
       raise ValueError('Document is not string!')
   document = document.strip()
   sentences = nltk.sent_tokenize(document)
   sentences = [sentence.strip() for sentence in sentences]
   return sentences

# sample document
text = """
FIFA was founded in 1904 to oversee international competition among the national associations of Belgium, 
Denmark, France, Germany, the Netherlands, Spain, Sweden, and Switzerland. Headquartered in Zürich, its 
membership now comprises 211 national associations. Member countries must each also be members of one of 
the six regional confederations into which the world is divided: Africa, Asia, Europe, North & Central America 
and the Caribbean, Oceania, and South America.
"""

# tokenize sentences
sentences = parse_document(text)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
# tag sentences and use nltk's Named Entity Chunker
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
ne_chunked_sents = [nltk.ne_chunk(tagged) for tagged in tagged_sentences]
# extract all named entities
named_entities = []
for ne_tagged_sentence in ne_chunked_sents:
   for tagged_tree in ne_tagged_sentence:
       # extract only chunks having NE labels
       if hasattr(tagged_tree, 'label'):
           entity_name = ' '.join(c[0] for c in tagged_tree.leaves()) #get NE name
           entity_type = tagged_tree.label() # get NE category
           named_entities.append((entity_name, entity_type))
           # get unique named entities
           named_entities = list(set(named_entities))

# store named entities in a data frame
entity_frame = pd.DataFrame(named_entities, columns=['Entity Name', 'Entity Type'])
# display results
print(entity_frame)

出力は次のとおりです。

        Entity Name   Entity Type
0              FIFA  ORGANIZATION
1   Central America  ORGANIZATION
2           Belgium           GPE
3         Caribbean      LOCATION
4              Asia           GPE
5            France           GPE
6           Oceania           GPE
7           Germany           GPE
8     South America           GPE
9           Denmark           GPE
10           Zürich           GPE
11           Africa        PERSON
12           Sweden           GPE
13      Netherlands           GPE
14            Spain           GPE
15      Switzerland           GPE
16            North           GPE
17           Europe           GPE

NLTKのNERタスクは一般に十分に完了していることがわかります。これは、FIFAを組織(ORGANIZATION)、ベルギー、アジアをGPEとして識別できますが、いくつかの不満な場所もあります。たとえば、中央アメリカは組織、ただし実際にはGPEである必要があります。アフリカを人として認識するためには、実際にはGPEである必要があります。

次に、Stanford NLPツールを使用してみました。このツールについては、主にStanford NERアノテーションツールを使用しています。このツールを使用する前に、Java(通常はJDK)をコンピューターにインストールし、Javaをシステムパスに追加して、英語のNERファイルパッケージをダウンロードする必要があります:stanford-ner-2018-10-16.zip(サイズは172MB)、ダウンロードアドレスはhttps://nlp.stanford.edu/software/CRF-NER.shtmlです。作成者のコンピュータを例にとると、Javaが置かれているパスはC:\ Program Files \ Java \ jdk1.8.0_161 \ bin \ java.exeであり、スタンフォードNERの解凍されたzipファイルをダウンロードした後のフォルダのパスはE:/です。 / stanford-ner-2018-10-16、以下に示すように:

img

E:// stanford-ner-2018-10-16

classiferフォルダーには次のファイルがあります。

img

E:// stanford-ner-2018-10-16 / classifiers

それらが表す意味は次のとおりです。

3クラス:場所、人、組織
4クラス:場所、人、組織、その他
7クラス:場所、人、組織、お金、パーセント、日付、時刻

Pythonを使用してStanford NERを実装できます。完全なコードは次のとおりです。

import re
from nltk.tag import StanfordNERTagger
import os
import pandas as pd
import nltk

def parse_document(document):
   document = re.sub('\n', ' ', document)
   if isinstance(document, str):
       document = document
   else:
       raise ValueError('Document is not string!')
   document = document.strip()
   sentences = nltk.sent_tokenize(document)
   sentences = [sentence.strip() for sentence in sentences]
   return sentences

# sample document
text = """
FIFA was founded in 1904 to oversee international competition among the national associations of Belgium, 
Denmark, France, Germany, the Netherlands, Spain, Sweden, and Switzerland. Headquartered in Zürich, its 
membership now comprises 211 national associations. Member countries must each also be members of one of 
the six regional confederations into which the world is divided: Africa, Asia, Europe, North & Central America 
and the Caribbean, Oceania, and South America.
"""

sentences = parse_document(text)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]

# set java path in environment variables
java_path = r'C:\Program Files\Java\jdk1.8.0_161\bin\java.exe'
os.environ['JAVAHOME'] = java_path
# load stanford NER
sn = StanfordNERTagger('E://stanford-ner-2018-10-16/classifiers/english.muc.7class.distsim.crf.ser.gz',
                       path_to_jar='E://stanford-ner-2018-10-16/stanford-ner.jar')

# tag sentences
ne_annotated_sentences = [sn.tag(sent) for sent in tokenized_sentences]
# extract named entities
named_entities = []
for sentence in ne_annotated_sentences:
   temp_entity_name = ''
   temp_named_entity = None
   for term, tag in sentence:
       # get terms with NE tags
       if tag != 'O':
           temp_entity_name = ' '.join([temp_entity_name, term]).strip() #get NE name
           temp_named_entity = (temp_entity_name, tag) # get NE and its category
       else:
           if temp_named_entity:
               named_entities.append(temp_named_entity)
               temp_entity_name = ''
               temp_named_entity = None

# get unique named entities
named_entities = list(set(named_entities))
# store named entities in a data frame
entity_frame = pd.DataFrame(named_entities, columns=['Entity Name', 'Entity Type'])
# display results
print(entity_frame)

出力は次のとおりです。

                Entity Name   Entity Type
0                      1904          DATE
1                   Denmark      LOCATION
2                     Spain      LOCATION
3   North & Central America  ORGANIZATION
4             South America      LOCATION
5                   Belgium      LOCATION
6                    Zürich      LOCATION
7           the Netherlands      LOCATION
8                    France      LOCATION
9                 Caribbean      LOCATION
10                   Sweden      LOCATION
11                  Oceania      LOCATION
12                     Asia      LOCATION
13                     FIFA  ORGANIZATION
14                   Europe      LOCATION
15                   Africa      LOCATION
16              Switzerland      LOCATION
17                  Germany      LOCATION

アフリカはLOCATIONとして認識され、1904は時間として認識されますが(NLTKでは認識されません)、北米および中央アメリカの認識はまだ間違っています。 ORGANIZATIONとして認識します。
 Stanford NERが必ずしもNLTK NERよりも効果的であるとは限らないことは注目に値します。2つのターゲットは異なるアルゴリズムを使用することが予想されるため、ニーズに応じて使用するツールを決定する必要があります。
 これで共有は終了です。今後機会があれば、HMM、CRF、ディープラーニングを使って名前付きエンティティの認識を実現していきます。

公式アカウントのソースコードデータセットとAIを一緒に取得します。

ここに画像の説明を挿入

参照:

https://github.com/skydark/nstools/blob/master/zhtools/zh_wiki.py#L8271

https://github.com/skydark/nstools/blob/master/zhtools/langconv.py

https://blog.csdn.net/lotusws/article/details/82934599

おすすめ

転載: blog.csdn.net/qq_46098574/article/details/108636465