In [1]:
#-*- coding:utf-8

00 文字列の逆順

文字列"streesed"の文字を逆に並べた文字列を得よ


In [2]:
strings = "stressed"
print(strings[::-1])


desserts

01 パタトクカシーー

「パタトクカシーー」と言う文字列の1, 3, 5, 7文字目を取り出して連結した文字列を得よ


In [3]:
strings1 = u"パタトクカシーー"
print(strings1[::2])


パトカー

02「パトカー」+「タクシー」=「パタトクカシーー」

「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ


In [4]:
strings_p = u"パトカー"
strings_t = u"タクシー"
strings_sum = ''
for p, t in zip(strings_p, strings_t):
    strings_sum += p + t
print(strings_sum)


パタトクカシーー

03. 円周率

"Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.


In [5]:
strings3 = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
count_list = [len(i) for i in strings3.split(' ')]
count_list


Out[5]:
[3, 1, 4, 1, 6, 9, 2, 7, 5, 3, 5, 8, 9, 7, 10]

04. 元素記号

"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.


In [6]:
strings4 = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
strings4 = strings4.replace('.', '')
strings4 = strings4.split(' ')
dictionary = {}
for i in range(len(strings4)):
    if i+1 in [1, 5, 6, 7, 8, 9, 15, 16, 19]:
        dictionary.update({strings4[i][:1]: strings4[i]})
    else:
        dictionary.update({strings4[i][:2]: strings4[i]})
print(dictionary)


{'K': 'King', 'S': 'Security', 'Ne': 'New', 'Si': 'Sign', 'P': 'Peace', 'Ar': 'Arthur', 'O': 'Oxidize', 'C': 'Could', 'N': 'Not', 'He': 'He', 'Cl': 'Clause', 'Al': 'Also', 'F': 'Fluorine', 'B': 'Boron', 'Na': 'Nations', 'Mi': 'Might', 'Ca': 'Can', 'Li': 'Lied', 'H': 'Hi', 'Be': 'Because'}

05 n-gram

与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.

この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ


In [7]:
def ngram(sequence, n, mode='c'):
    if mode == 'c':
        return [sequence[i:i+n] for i in range(len(sequence)-1)]
    elif mode == 'w':
        sequence  = [s.strip(',.') for s in sequence.split(' ')] # スペースや記号を除去した単語リストの生成
        return [tuple(sequence[i:i+n]) for i in range(len(sequence)-1)]
        

sequence = "I am an NLPer"
print(ngram(sequence, 2))
print(ngram(sequence, 2, 'w'))


['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']
[('I', 'am'), ('am', 'an'), ('an', 'NLPer')]

06. 集合

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


In [8]:
X = set(ngram('paraparaparadise', 2))
Y = (ngram('paragraph', 2))
print(X.intersection(Y))
print(X.union(Y))
print(X.difference(Y))
print('se' in X)
print('se' in Y)


{'ap', 'ar', 'pa', 'ra'}
{'ap', 'di', 'ad', 'ra', 'gr', 'ag', 'pa', 'ph', 'ar', 'se', 'is'}
{'di', 'ad', 'se', 'is'}
True
False

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

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


In [9]:
#-*- coding:utf-8 -*-
def print_template(x, y, z):
    return u'%s時の%s%s' % (x, y, z)

template = print_template(12, u'気温', 22.4)
print(template)


12時の気温は22.4

08. 暗号文

与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.

英小文字ならば(219 - 文字コード)の文字に置換 その他の文字はそのまま出力 この関数を用い,英語のメッセージを暗号化・復号化せよ.


In [10]:
def cipher(sequence):
    return "".join((map(str, [chr(219-ord(i)) if i.islower() else i for i in sequence])))

strings = "I am an NLPer"
encryption = cipher(strings)
decryption = cipher(encryption)
print(encryption)
print(decryption)


I zn zm NLPvi
I am an NLPer

09. Typoglycemia

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


In [11]:
import random
sequence = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind."
[s[0]+"".join(map(str, random.sample(s[1:-1], len(s)-2)))+s[-1] if len(s) >= 5 \
 else str(s) for s in sequence.split(' ')]


Out[11]:
['I',
 "clound't",
 'bivelee',
 'that',
 'I',
 'cluod',
 'aaullcty',
 'ursetnadnd',
 'what',
 'I',
 'was',
 'rdneiag',
 ':',
 'the',
 'pmaonneehl',
 'pewor',
 'of',
 'the',
 'human',
 'mndi.']

In [ ]: