唐突に変な話ですが、「エロ本」の形態素解析、unidic では「エロボン」として登録されているので1語になるんですが、ipa辞書を使うと「エロ」「ホン」と2語になるんですね。
さて、今回から言語処理100本ノック第6章に入ります。
調べたことメモ
関数とかの名前の付け方
忘れとったわあ。 👉 Python命名規則一覧 - Qiita
対象 | ルール | 例 |
---|---|---|
関数 | 全小文字 + アンダースコア区切り | my_favorite_funcion |
変数 | 全小文字 + アンダースコア区切り | my_favorite_instance |
ファイルの全内容を1文字ずつ読む
参考 👉 Python でテキストファイルを読み込む | まくまくPythonノート
with open(filename, encoding='utf-8') as f: content = f.read() for char in content: nanka_suru(char)
1行ずつ読むことにしたので、使わなかったけど。
英大文字を判定する
判定する文字列char
について、str.isupper(char)
として、char
がすべて大文字ならTrue
、それ以外はFalse
。
参考 👉 Pythonで大文字・小文字を操作する文字列メソッド一覧 | note.nkmk.me
言語処理100本ノック #050
第6章: 英語テキストの処理
英語のテキスト(nlp.txt)に対して,以下の処理を実行せよ.
50. 文区切り
(. or ; or : or ? or !) → 空白文字 → 英大文字というパターンを文の区切りと見なし,入力された文書を1行1文の形式で出力せよ.
指定されたパターンには「改行」や「ファイルの終端」が含まれていないのですが、含むことにします。
独自ルール
- (. or ; or : or ? or !)以外の文字 → 改行 というパターンは無視する(タイトル等)
- (. or ; or : or ? or !) → {(空白文字 → 英大文字) or 改行 or ファイルの終端)} というパターンを文の区切りとみなす
完成
# knock_050.py nlp_file = 'nlp.txt' def get_sentence(line): sentence = '' for i, char in enumerate(line): if char in ['.', ';', ':', '?', '!']: sentence += char if i+3 > len(line): # 文末文字 -> 改行 yield sentence sentence = '' elif line[i+1] == ' ': if str.isupper(line[i+2]): # 文末文字 -> 空白 -> 英大文字 yield sentence sentence = '' elif char == ' ' and len(sentence) <1: # 文の間の空白は読み飛ばす pass else: sentence += char if len(sentence) > 1: # タイトル行の処理はここで pass def file_to_sentence(readfile): with open(readfile, encoding='utf-8') as f: for line in f: for sentence in get_sentence(line): yield sentence if __name__ == '__main__': for sentence in file_to_sentence(nlp_file): print(sentence)
結果
# knock_050.py >> knock_050.txt (5行目まで) Natural language processing (NLP) is a field of computer science, artificial intelligence, and linguistics concerned with the interactions between computers and human (natural) languages. As such, NLP is related to the area of humani-computer interaction. Many challenges in NLP involve natural language understanding, that is, enabling computers to derive meaning from human or natural language input, and others involve natural language generation. The history of NLP generally starts in the 1950s, although work can be found from earlier periods. In 1950, Alan Turing published an article titled "Computing Machinery and Intelligence" which proposed what is now called the Turing test as a criterion of intelligence.
言語処理100本ノック #051
51. 単語の切り出し
空白を単語の区切りとみなし,50の出力を入力として受け取り,1行1単語の形式で出力せよ.ただし,文の終端では空行を出力せよ.
完成
# # knock_051.py (メイン部分のみ knock_050.py から書き換え) if __name__ == '__main__': for sentence in file_to_sentence(nlp_file): for word in sentence.split(' '): print(word) print('\n', end='')
結果
# python knock_051.py >> knock_051.txt (30行目まで) Natural language processing (NLP) is a field of computer science, artificial intelligence, and linguistics concerned with the interactions between computers and human (natural) languages. As such, NLP is related