私的メモ

仕事で調べた技術情報をポストしています。

カテゴリ: nltk

昨日ChasenCorpusReaderを利用して取り込んだ日本語データを確認してみます。


len(zenbun_corpus.words())
413

len(set(zenbun_corpus.words()))
171

PlaintextCorpusReaderから取り込んだ時が前文で320語 単語数169でした。
グラフ描画してみます。

frequency = nltk.FreqDist(zenbun_corpus.words())
frequency.plot(30,cumulative=True)
071002


全文の中から単語を検索してみます。


data_t = Text( w for w in zenbun_corpus.words() )
data_t.concordance('国民')
Displaying 11 of 11 matches:
                                      国民 は 、 正当 に 選挙 さ れ た 国会 における 代表 者 を通じて 行
じて 行動 し 、 われ ら と われ ら の 子孫 の ため に 、 諸 国民 と の 協和 による 成果 と 、 わが国 全土 に わ たつ て 自由 
こと の ない やう に する こと を 決意 し 、 ここ に 主権 が 国民 に 存する こと を 宣言 し 、 この 憲法 を 確定 する 。 そもそ
 を 宣言 し 、 この 憲法 を 確定 する 。 そもそも 国政 は 、 国民 の 厳粛 な 信託 による もの てあつ て 、 その 権威 は 国民 に
、 国民 の 厳粛 な 信託 による もの てあつ て 、 その 権威 は 国民 に 由来 し 、 その 権力 は 国民 の 代表 者 が これ を 行使 
の てあつ て 、 その 権威 は 国民 に 由来 し 、 その 権力 は 国民 の 代表 者 が これ を 行使 し 、 その 福利 は 国民 が これ 
 権力 は 国民 の 代表 者 が これ を 行使 し 、 その 福利 は 国民 が これ を 享受 する 。 これ は 人類 普遍 の 原理 で あり 、
に 反する 一切 の 憲法 、 法令 及び 詔勅 を 排除 する 。 日本 国民 は 、 恒久 の 平和 を 念願 し 、 人間 相互 の 関係 を 支配 
 な 理想 を 深く 自覚 する ので あ つて 、 平和 を 愛する 諸 国民 の 公正 と 信義 に 信頼 し て 、 われ ら の 安全 と 生存 を
 ある 地位 を 占め たい と 思ふ 。 われ ら は 、 全 世界 の 国民 が 、 ひとしく 恐怖 と 欠乏 から 免 かれ 、 平和 の うち に 
係 に 立た う と する 各国 の 責務 で ある と 信ずる 。 日本 国民 は 、 国家 の 名誉 に かけ 、 全力 を あげ て この 崇高 な 

出現数カウント
data_t.count('国民')
11

data_t.count('平和')
4

では単語の出現をdispersion_plotしてみます。

data_t.dispersion_plot(['国民','平和'])
071001



昨日に引き続き日本国憲法前文でnltk操作の確認をしてみます。

昨日はprint(' '.join(jp_text.words()))で内容の確認までしました。

単語分割結果をプロットしいきます。


まずは文章全体の単語数を見てみます。

len(jp_text.words())
320

ワード種別を見てみます。
len(set(jp_text.words()))
169

では文章をFreqDistに代入します。
frequency = nltk.FreqDist(jp_text.words())

累積グラフで表示してみます。

frequency.plot(30,cumulative=True)
070601

文章をクリーンアップしていないのでいろいろ入っていますが、問題無くいけているようです。

累積させないとこうなりました。
070602









日本国憲法前文をあらかじめzenbun.txtとしてテキストファイルに落としておきます。

文章を読み込みます。
jp_text = PlaintextCorpusReader(".",r'zenbun.txt',
                              encoding='utf-8',
                              para_block_reader=read_line_block,
                              sent_tokenizer=sent_tokenizer,
                              word_tokenizer=chartype_tokenizer)
読み込んだ文章を確認してみます。
print(jp_text.raw())
前 文
日本国民は、正当に選挙された国会における代表者を通じて行動し、われらとわれらの子孫のために、諸国民との協和による成果と、わが国全土にわたつて自由のもたらす恵沢を確保し、政府の行為によつて再び戦争の惨禍が起ることのないやうにすることを決意し、ここに主権が国民に存することを宣言し、この憲法を確定する。そもそも国政は、国民の厳粛な信託によるものてあつて、その権威は国民に由来し、その権力は国民の代表者がこれを行使し、その福利は国民がこれを享受する。これは人類普遍の原理であり、この憲法は、かかる原理に基くものである。われらは、これに反する一切の憲法、法令及び詔勅を排除する。
日本国民は、恒久の平和を念願し、人間相互の関係を支配する崇高な理想を深く自覚するのであつて、平和を愛する諸国民の公正と信義に信頼して、われらの安全と生存を保持しようと決意した。われらは、平和を維持し、専制と隷従、圧迫と偏狭を地上から永遠に除去しようと努めてゐる国際社会において、名誉ある地位を占めたいと思ふ。われらは、全世界の国民が、ひとしく恐怖と欠乏から免かれ、平和のうちに生存する権利を有することを確認する。
われらは、いづれの国家も、自国のことのみに専念して他国を無視してはならないのであつて、政治道徳の法則は、普遍的なものであり、この法則に従ふことは、自国の主権を維持し、他国と対等関係に立たうとする各国の責務であると信ずる。
日本国民は、国家の名誉にかけ、全力をあげてこの崇高な理想と目的を達成することを誓ふ。

ワードごとにスペース区切りで表示してみます。
print(' '.join( jp_text.words()))
前   文 
 日本国民 は 、 正当 に 選挙 された 国会 における 代表者 を 通 じて 行動 し 、 われらとわれらの 子孫 のために 、 諸国民 との 協和 による 成果 と 、 わが 国全土 にわたつて 自由 のもたらす 恵沢 を 確保 し 、 政府 の 行為 によつて 再 び 戦争 の 惨禍 が 起 ることのないやうにすることを 決意 し 、 ここに 主権 が 国民 に 存 することを 宣言 し 、 この 憲法 を 確定 する 。 そもそも 国政 は 、 国民 の 厳粛 な 信託 によるものてあつて 、 その 権威 は 国民 に 由来 し 、 その 権力 は 国民 の 代表者 がこれを 行使 し 、 その 福利 は 国民 がこれを 享受 する 。 これは 人類普遍 の 原理 であり 、 この 憲法 は 、 かかる 原理 に 基 くものである 。 われらは 、 これに 反 する 一切 の 憲法 、 法令及 び 詔勅 を 排除 する 。
 日本国民 は 、 恒久 の 平和 を 念願 し 、 人間相互 の 関係 を 支配 する 崇高 な 理想 を 深 く 自覚 するのであつて 、 平和 を 愛 する 諸国民 の 公正 と 信義 に 信頼 して 、 われらの 安全 と 生存 を 保持 しようと 決意 した 。 われらは 、 平和 を 維持 し 、 専制 と 隷従 、 圧迫 と 偏狭 を 地上 から 永遠 に 除去 しようと 努 めてゐる 国際社会 において 、 名誉 ある 地位 を 占 めたいと 思 ふ 。 われらは 、 全世界 の 国民 が 、 ひとしく 恐怖 と 欠乏 から 免 かれ 、 平和 のうちに 生存 する 権利 を 有 することを 確認 する 。
 われらは 、 いづれの 国家 も 、 自国 のことのみに 専念 して 他国 を 無視 してはならないのであつて 、 政治道徳 の 法則 は 、 普遍的 なものであり 、 この 法則 に 従 ふことは 、 自国 の 主権 を 維持 し 、 他国 と 対等関係 に 立 たうとする 各国 の 責務 であると 信 ずる 。
 日本国民 は 、 国家 の 名誉 にかけ 、 全力 をあげてこの 崇高 な 理想 と 目的 を 達成 することを 誓 ふ 。

こちらでnltkで日本語をワード分割する方法が紹介されていたので試してみました。

モジュールをインポートします。
import nltk
from nltk.corpus.reader import *
from nltk.corpus.reader.util import *
from nltk.text import Text

全角記号を登録しておきます。
sent_tokenizer = nltk.RegexpTokenizer(u'[^ ()『』【】「」!?。]*[!?。]')

トークナイザーに日本語文字を登録します。
chartype_tokenizer = nltk.RegexpTokenizer(u'([ぁ-んー]+|[ァ-ンー]+|[\u4e00-\u9FFF]+|[^ぁ-んァ-ンー\u4e00-\u9FFF]+)')

日本国憲法前文をあらかじめzenbun.txtとしてテキストファイルに落としておきます。

文章を読み込みます。
jp_text = PlaintextCorpusReader(".",r'zenbun.txt',
                              encoding='utf-8',
                              para_block_reader=read_line_block,
                              sent_tokenizer=sent_tokenizer,
                              word_tokenizer=chartype_tokenizer)
読み込んだ文章を確認してみます。
print(jp_text.raw())
前 文
日本国民は、正当に選挙された国会における代表者を通じて行動し、われらとわれらの子孫のために、諸国民との協和による成果と、わが国全土にわたつて自由のもたらす恵沢を確保し、政府の行為によつて再び戦争の惨禍が起ることのないやうにすることを決意し、ここに主権が国民に存することを宣言し、この憲法を確定する。そもそも国政は、国民の厳粛な信託によるものてあつて、その権威は国民に由来し、その権力は国民の代表者がこれを行使し、その福利は国民がこれを享受する。これは人類普遍の原理であり、この憲法は、かかる原理に基くものである。われらは、これに反する一切の憲法、法令及び詔勅を排除する。
日本国民は、恒久の平和を念願し、人間相互の関係を支配する崇高な理想を深く自覚するのであつて、平和を愛する諸国民の公正と信義に信頼して、われらの安全と生存を保持しようと決意した。われらは、平和を維持し、専制と隷従、圧迫と偏狭を地上から永遠に除去しようと努めてゐる国際社会において、名誉ある地位を占めたいと思ふ。われらは、全世界の国民が、ひとしく恐怖と欠乏から免かれ、平和のうちに生存する権利を有することを確認する。
われらは、いづれの国家も、自国のことのみに専念して他国を無視してはならないのであつて、政治道徳の法則は、普遍的なものであり、この法則に従ふことは、自国の主権を維持し、他国と対等関係に立たうとする各国の責務であると信ずる。
日本国民は、国家の名誉にかけ、全力をあげてこの崇高な理想と目的を達成することを誓ふ。

ワードごとにスペース区切りで表示してみます。
print(' '.join( jp_text.words()))
前   文 
 日本国民 は 、 正当 に 選挙 された 国会 における 代表者 を 通 じて 行動 し 、 われらとわれらの 子孫 のために 、 諸国民 との 協和 による 成果 と 、 わが 国全土 にわたつて 自由 のもたらす 恵沢 を 確保 し 、 政府 の 行為 によつて 再 び 戦争 の 惨禍 が 起 ることのないやうにすることを 決意 し 、 ここに 主権 が 国民 に 存 することを 宣言 し 、 この 憲法 を 確定 する 。 そもそも 国政 は 、 国民 の 厳粛 な 信託 によるものてあつて 、 その 権威 は 国民 に 由来 し 、 その 権力 は 国民 の 代表者 がこれを 行使 し 、 その 福利 は 国民 がこれを 享受 する 。 これは 人類普遍 の 原理 であり 、 この 憲法 は 、 かかる 原理 に 基 くものである 。 われらは 、 これに 反 する 一切 の 憲法 、 法令及 び 詔勅 を 排除 する 。
 日本国民 は 、 恒久 の 平和 を 念願 し 、 人間相互 の 関係 を 支配 する 崇高 な 理想 を 深 く 自覚 するのであつて 、 平和 を 愛 する 諸国民 の 公正 と 信義 に 信頼 して 、 われらの 安全 と 生存 を 保持 しようと 決意 した 。 われらは 、 平和 を 維持 し 、 専制 と 隷従 、 圧迫 と 偏狭 を 地上 から 永遠 に 除去 しようと 努 めてゐる 国際社会 において 、 名誉 ある 地位 を 占 めたいと 思 ふ 。 われらは 、 全世界 の 国民 が 、 ひとしく 恐怖 と 欠乏 から 免 かれ 、 平和 のうちに 生存 する 権利 を 有 することを 確認 する 。
 われらは 、 いづれの 国家 も 、 自国 のことのみに 専念 して 他国 を 無視 してはならないのであつて 、 政治道徳 の 法則 は 、 普遍的 なものであり 、 この 法則 に 従 ふことは 、 自国 の 主権 を 維持 し 、 他国 と 対等関係 に 立 たうとする 各国 の 責務 であると 信 ずる 。
 日本国民 は 、 国家 の 名誉 にかけ 、 全力 をあげてこの 崇高 な 理想 と 目的 を 達成 することを 誓 ふ 。

7月4日なので練習を兼ねてアメリカ独立宣言を簡易nltkしてみます。

モジュールをインポートします。

import nltk
from nltk import word_tokenize,sent_tokenize

独立宣言全文はこちらから抽出しています。
text="IN CONGRESS, JULY 4, 1776The unanimous Declaration of the thirteen united States of AmericaWhen in the Course of human events it becomes necessary for one people to dissolve the political bands which have connected them with another and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness. — That to secure these rights, Governments are instituted among Men, deriving their just powers from the consent of the governed, — That whenever any Form of Government becomes destructive of these ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments long established should not be changed for light and transient causes; and accordingly all experience hath shewn that mankind are more disposed to suffer, while evils are sufferable than to right themselves by abolishing the forms to which they are accustomed. But when a long train of abuses and usurpations, pursuing invariably the same Object evinces a design to reduce them under absolute Despotism, it is their right, it is their duty, to throw off such Government, and to provide new Guards for their future security. — Such has been the patient sufferance of these Colonies; and such is now the necessity which constrains them to alter their former Systems of Government. The history of the present King of Great Britain is a history of repeated injuries and usurpations, all having in direct object the establishment of an absolute Tyranny over these States. To prove this, let Facts be submitted to a candid world.He has refused his Assent to Laws, the most wholesome and necessary for the public good.He has forbidden his Governors to pass Laws of immediate and pressing importance, unless suspended in their operation till his Assent should be obtained; and when so suspended, he has utterly neglected to attend to them.He has refused to pass other Laws for the accommodation of large districts of people, unless those people would relinquish the right of Representation in the Legislature, a right inestimable to them and formidable to tyrants only.He has called together legislative bodies at places unusual, uncomfortable, and distant from the depository of their Public Records, for the sole purpose of fatiguing them into compliance with his measures.He has dissolved Representative Houses repeatedly, for opposing with manly firmness his invasions on the rights of the people.He has refused for a long time, after such dissolutions, to cause others to be elected, whereby the Legislative Powers, incapable of Annihilation, have returned to the People at large for their exercise; the State remaining in the mean time exposed to all the dangers of invasion from without, and convulsions within.He has endeavoured to prevent the population of these States; for that purpose obstructing the Laws for Naturalization of Foreigners; refusing to pass others to encourage their migrations hither, and raising the conditions of new Appropriations of Lands.He has obstructed the Administration of Justice by refusing his Assent to Laws for establishing Judiciary Powers.He has made Judges dependent on his Will alone for the tenure of their offices, and the amount and payment of their salaries.He has erected a multitude of New Offices, and sent hither swarms of Officers to harass our people and eat out their substance.He has kept among us, in times of peace, Standing Armies without the Consent of our legislatures.He has affected to render the Military independent of and superior to the Civil Power.He has combined with others to subject us to a jurisdiction foreign to our constitution, and unacknowledged by our laws; giving his Assent to their Acts of pretended Legislation:For quartering large bodies of armed troops among us:For protecting them, by a mock Trial from punishment for any Murders which they should commit on the Inhabitants of these States:For cutting off our Trade with all parts of the world:For imposing Taxes on us without our Consent:For depriving us in many cases, of the benefit of Trial by Jury:For transporting us beyond Seas to be tried for pretended offences:For abolishing the free System of English Laws in a neighbouring Province, establishing therein an Arbitrary government, and enlarging its Boundaries so as to render it at once an example and fit instrument for introducing the same absolute rule into these ColoniesFor taking away our Charters, abolishing our most valuable Laws and altering fundamentally the Forms of our Governments:For suspending our own Legislatures, and declaring themselves invested with power to legislate for us in all cases whatsoever.He has abdicated Government here, by declaring us out of his Protection and waging War against us.He has plundered our seas, ravaged our coasts, burnt our towns, and destroyed the lives of our people.He is at this time transporting large Armies of foreign Mercenaries to compleat the works of death, desolation, and tyranny, already begun with circumstances of Cruelty & Perfidy scarcely paralleled in the most barbarous ages, and totally unworthy the Head of a civilized nation.He has constrained our fellow Citizens taken Captive on the high Seas to bear Arms against their Country, to become the executioners of their friends and Brethren, or to fall themselves by their Hands.He has excited domestic insurrections amongst us, and has endeavoured to bring on the inhabitants of our frontiers, the merciless Indian Savages whose known rule of warfare, is an undistinguished destruction of all ages, sexes and conditions.In every stage of these Oppressions We have Petitioned for Redress in the most humble terms: Our repeated Petitions have been answered only by repeated injury. A Prince, whose character is thus marked by every act which may define a Tyrant, is unfit to be the ruler of a free people.Nor have We been wanting in attentions to our British brethren. We have warned them from time to time of attempts by their legislature to extend an unwarrantable jurisdiction over us. We have reminded them of the circumstances of our emigration and settlement here. We have appealed to their native justice and magnanimity, and we have conjured them by the ties of our common kindred to disavow these usurpations, which would inevitably interrupt our connections and correspondence. They too have been deaf to the voice of justice and of consanguinity. We must, therefore, acquiesce in the necessity, which denounces our Separation, and hold them, as we hold the rest of mankind, Enemies in War, in Peace Friends.We, therefore, the Representatives of the united States of America, in General Congress, Assembled, appealing to the Supreme Judge of the world for the rectitude of our intentions, do, in the Name, and by Authority of the good People of these Colonies, solemnly publish and declare, That these united Colonies are, and of Right ought to be Free and Independent States, that they are Absolved from all Allegiance to the British Crown, and that all political connection between them and the State of Great Britain, is and ought to be totally dissolved; and that as Free and Independent States, they have full Power to levy War, conclude Peace, contract Alliances, establish Commerce, and to do all other Acts and Things which Independent States may of right do. — And for the support of this Declaration, with a firm reliance on the protection of Divine Providence, we mutually pledge to each other our Lives, our Fortunes, and our sacred Honor.New Hampshire:Josiah Bartlett, William Whipple, Matthew ThorntonMassachusetts:John Hancock, Samuel Adams, John Adams, Robert Treat Paine, Elbridge GerryRhode Island:Stephen Hopkins, William ElleryConnecticut:Roger Sherman, Samuel Huntington, William Williams, Oliver WolcottNew York:William Floyd, Philip Livingston, Francis Lewis, Lewis MorrisNew Jersey:Richard Stockton, John Witherspoon, Francis Hopkinson, John Hart, Abraham ClarkPennsylvania:Robert Morris, Benjamin Rush, Benjamin Franklin, John Morton, George Clymer, James Smith, George Taylor, James Wilson, George RossDelaware:Caesar Rodney, George Read, Thomas McKeanMaryland:Samuel Chase, William Paca, Thomas Stone, Charles Carroll of CarrolltonVirginia:George Wythe, Richard Henry Lee, Thomas Jefferson, Benjamin Harrison, Thomas Nelson, Jr., Francis Lightfoot Lee, Carter BraxtonNorth Carolina:William Hooper, Joseph Hewes, John PennSouth Carolina:Edward Rutledge, Thomas Heyward, Jr., Thomas Lynch, Jr., Arthur MiddletonGeorgia:Button Gwinnett, Lyman Hall, George Walton"

文章をトークン化します。

token = nltk.word_tokenize(text)


Stopwordsを呼び出して、記号と一緒に除外します。

stop_words = nltk.corpus.stopwords.words('english')
symbol = ["'", '"', ':', ';', '.', ',', '-', '!', '?', "'s"]
clean_frequency = nltk.FreqDist(w.lower() for w in token if w.lower() not in stop_words + symbol)
積算値で出現数をグラフ化します。
clean_frequency.plot(30,cumulative=True)
070401

積算なしも見てみます。

clean_frequency.plot(30,cumulative=False)
070402

Laws,States,people,rights,joinとか、stemmingなしなのでgovernmentとgovernmentsがあったりしますね。

ついでにセンチメント分析を適用してみましょう。
モジュールを読み込みます。
from nltk.sentiment.vader import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
analyzer.polarity_scores(text)
{'compound': 0.9225, 'neg': 0.078, 'neu': 0.834, 'pos': 0.088}
公式文書なので中立がほとんどですかね。


nltkで単語出現率を計算してみます。

モジュールをインポートします。

import nltk
from nltk.book import *

nltk.bookから白鯨を選択します。

語数を確認してみます。
len(text1)
260819

重複を除いた語数を確認します。
len(set(text1))
19317

単語セットの内容を確認します。
最初の278個は記号の羅列でした。
sorted(set(text1))[279:290]
['A',
 'ABOUT',
 'ACCOUNT',
 'ADDITIONAL',
 'ADVANCING',
 'ADVENTURES',
 'AFFGHANISTAN',
 'AFRICA',
 'AFTER',
 'AGAINST',
 'AHAB']
テキストの中の重複率を見てみます。
len(set(text1)) / len(text1)
0.07406285585022564

単語数をカウントしてみます。
text1.count('a')
4569

ここのカウントで気を付けなければいけないのが、count()は大文字小文字が区別される事。
大文字で検索すると別の結果になります。
text1.count('A')
167

試しにconcordanceで見てみます。
text1.concordance('a')
Displaying 25 of 4736 matches:
                                       a Late Consumptive Usher to a Grammar Sc
                                       a Grammar School ) The pale Usher -- thr
g his old lexicons and grammars , with a queer handkerchief , mockingly embelli
thers , and to teach them by what name a whale - fish is to be called in our to
tely from the Dut . and Ger . WALLEN ; A . S . WALW - IAN , to roll , to wallow
, ERROMANGOAN . EXTRACTS ( Supplied by a Sub - Sub - Librarian ). It will be se
ainstaking burrower and grub - worm of a poor devil of a Sub - Sub appears to h
wer and grub - worm of a poor devil of a Sub - Sub appears to have gone through
aluable or entertaining , as affording a glancing bird ' s eye view of what has
wn . So fare thee well , poor devil of a Sub - Sub , whose commentator I am . T
les ." -- GENESIS . " Leviathan maketh a path to shine after him ; One would th
" -- JOB . " Now the Lord had prepared a great fish to swallow up Jonah ." -- J
o days on the sea , when about sunrise a great many Whales and other monsters o
peared . Among the former , one was of a most monstrous size . ... This came to
 , and beating the sea before him into a foam ." -- TOOKE ' S LUCIAN . " THE TR
." " He visited this country also with a view of catching horse - whales , whic
N DOWN FROM HIS MOUTH BY KING ALFRED , A . D . 890 . " And whereas all the othe
 bruise ." -- KING HENRY . " Very like a whale ." -- HAMLET . " Which to secure
the motion of whose vast bodies can in a peaceful calm trouble the ocean til it
in his side he wears , And on his back a grove of pikes appears ." -- WALLER ' 
 created that great Leviathan , called a Commonwealth or State --( in Latin , C
it without chewing , as if it had been a sprat in the mouth of a whale ." -- PI
if it had been a sprat in the mouth of a whale ." -- PILGRIM ' S PROGRESS . " T
creatures , in the deep Stretched like a promontory sleeps or swims , And seems
promontory sleeps or swims , And seems a moving land ; and at his gills Draws i

では全体の単語数からの出現数を見てみます。
100 * (text1.count('A') + text1.count('a')) / len(text1)
1.815818632845


↑このページのトップヘ