LoginSignup
3
4

More than 5 years have passed since last update.

言語処理100本ノック 06~09

Last updated at Posted at 2015-08-04

06. 集合

"paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.

nlp06.py
#!usr/bin/env python
#coding:UTF-8
def char_ngram(n,seq):
    li = []
    for i in range(len(seq)):
        li.append(seq[i:i+n])
    return li

seq1 = "paraparaparadise"
seq2 = "paragraph"

X = char_ngram(2,seq1)
Y = char_ngram(2,seq2)
Z = ['se']

logical_sum = set(X).union(Y)
logical_product = set(X).intersection(Y)
logical_difference = set(X).symmetric_difference(Y)
print "和集合:",
print logical_sum
print "積集合:",
print logical_product
print "差集合:",
print logical_difference
print "seというbi-gramはXに含まれるか",
print('se' in X)
print "seというbi-gramはYに含まれるか",
print('se' in Y)

実行結果
和集合: set(['e', 'ad', 'ag', 'di', 'h', 'is', 'ap', 'pa', 'ra', 'ph', 'ar', 'se', 'gr'])
積集合: set(['ap', 'pa', 'ar', 'ra'])
差集合: set(['e', 'gr', 'ag', 'di', 'h', 'is', 'ph', 'se', 'ad'])
seというbi-gramはXに含まれるか True
seというbi-gramはYに含まれるか False

07. テンプレートによる文生成

引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ.

nlp07.py
def combine(x,y,z):
    s1 = "時の"
    s2 = "は"
    seq = str(x)+s1+str(y)+s2+str(z)
    return seq
x = 12
y = "気温"
z = 22.4
print combine(x,y,z)

実行結果
12時の気温は22.4

08. 暗号文

与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
英小文字ならば(219 - 文字コード)の文字に置換
その他の文字はそのまま出力
この関数を用い,英語のメッセージを暗号化・復号化せよ.

nlp08.py
#!usr/bin/env python
#coding:UTF-8
def cipher(str):
    enc = ""
    for char in str:
        if 97 <= ord(char)<= 123:
            enc +=chr(219-ord(char))
        else:
            enc +=char
    return enc
str = "Machine Learning"
print cipher(str)#暗号化
print cipher(cipher(str))#複合化

実行結果
Mzxsrmv Lvzimrmt
Machine Learning

09. Typoglycemia

スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,その実行結果を確認せよ.

nlp09.py
#!usr/bin/env python
#coding:UTF-8
#Typoglycemia
import random
def Typo(word): 
    if len(word)>4:
        wordli = list(word[1:-1])
        random.shuffle(wordli)
        neword = word[0] + ''.join(wordli)+ word[-1]
        return neword
    else:
        return word

str="I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind."

typostr=""
for word in str.replace("."," .").split():
    typostr +=" "+Typo(word)
print(typostr)

実行結果
I clundo't bivelee that I colud allctuay uedtnasrnd what I was riednag : the phnoneeaml peowr of the hmaun mind .

typostr +=" "+Typo(word)の部分がもっといい書き方があるはず、、

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4