1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

言語処理100本ノック(2020): 00-09

Posted at

第1章: 準備運動

00. 文字列の逆順

s = "stressed"
print(s[::-1])

01. 「パタトクカシーー」


"""
01. 「パタトクカシーー」
「パタトクカシーー」という文字列の1,3,5,7文字目を取り出して連結した文字列を得よ.
"""
s = "パタトクカシーー"
print(s[::2])
# パトカー

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

from functools import reduce

s1 = "パトカー"
s2 = "タクシー"

# method 1
res = [s1[i] + s2[i] for i in range(len(s1))]
print("".join(res))
# パタトクカシーー

# method 2
res = [a + b for a, b in zip(s1, s2)]
print("".join(res))

# method 3
res = reduce(lambda a, b: a + b, zip(s1, s2))
print(res)


# reduce
def do_sum(x1, x2):
    return x1 + x2


print(reduce(do_sum, [1, 2, 3, 4]))  # 10
# (((1 + 2) + 3) + 4) => 10

03. 円周率

"""
03. 円周率
“Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”
という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
"""
s = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
for c in [",", "."]:
    s = s.replace(c, "")
words = s.split(" ")

print([len(word) for word in words])
# [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

04. 元素記号

"""
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文字を取り出し,
取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
"""

# Get words
s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
for c in [",", "."]:
    s = s.replace(c, "")
words = s.split(" ")

# Make index
one_character_pos = [x - 1 for x in (1, 5, 6, 7, 8, 9, 15, 16, 19)]
index = {}
for i, word in enumerate(words):
    if i in one_character_pos:
        index[word[0]] = i
    else:
        index[word[:2]] = i
print(index)
# {'H': 0, 'He': 1, 'Li': 2, 'Be': 3, 'B': 4, 'C': 5, 'N': 6, 'O': 7, 'F': 8, 'Ne': 9, 'Na': 10, 'Mi': 11, 'Al': 12, 'Si': 13, 'P': 14, 'S': 15, 'Cl': 16, 'Ar': 17, 'K': 18, 'Ca': 19}

05. n-gram

"""
05. n-gram
与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.
この関数を用い,”I am an NLPer”という文から単語bi-gram,文字bi-gramを得よ.
"""
from typing import List, Sequence


def word_bigram(words: List[str]):
    return [words[i : i + 2] for i in range(len(words) - 1)]


def char_bigram(chars: str):
    return [chars[i : i + 2] for i in range(len(chars) - 1)]


s = "I am an NLPer"
print(word_bigram(s.split(" ")))
print(char_bigram(s))
# [['I', 'am'], ['am', 'an'], ['an', 'NLPer']]
# ['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']


# Generalization
def n_gram(seq: Sequence, n: int):
    return [seq[i : i + n] for i in range(len(seq) - n + 1)]


print(n_gram(s.split(" "), n=2))
print(n_gram(s, n=2))
# [['I', 'am'], ['am', 'an'], ['an', 'NLPer']]
# ['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']

06. 集合

"""
06. 集合
“paraparaparadise”と”paragraph”に含まれる文字bi-gramの集合を,それぞれ,
XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,’se’というbi-gramがXおよびYに含まれるかどうかを調べよ.
https://www.javadrive.jp/python/set/index6.html#section1
"""

from typing import Sequence


# Generalization
def n_gram(seq: Sequence, n: int):
    return [seq[i : i + n] for i in range(len(seq) - n + 1)]


x = set(n_gram("paraparaparadise", n=2))
y = set(n_gram("paragraph", n=2))
# x {'ar', 'ra', 'is', 'ap', 'pa', 'di', 'ad', 'se'}
# y {'ar', 'ra', 'is', 'ap', 'pa', 'di', 'ad', 'se'}

union_res = x.union(y)
intersection_res = x.intersection(y)
difference_res = x.difference(y)
print(union_res)
print(intersection_res)
print(difference_res)
# {'ar', 'ad', 'se', 'ph', 'pa', 'is', 'gr', 'di', 'ap', 'ra', 'ag'}
# {'ra', 'ar', 'pa', 'ap'}
# {'se', 'di', 'ad', 'is'}

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

"""
07. テンプレートによる文生成Permalink
引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.
さらに,x=12, y=”気温”, z=22.4として,実行結果を確認せよ.
"""


def generate(x, y, z):
    return f"{x}時の{y}{z}"


x = 12
y = "気温"
z = 22.4

print(generate(x, y, z))
# 12時の気温は22.4

08. 暗号文

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

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

Method:
ord:文字→アスキーコード
chr:アスキーコード→文字
"""


def cipher(string: str):
    result = ""
    for s in string:
        if s.islower():
            result += chr(219 - ord(s))
        else:
            result += s
    return result


print(cipher("This is a encrypted message"))
print(cipher("Tsrh rh z vmxibkgvw nvhhztv"))
# Tsrh rh z vmxibkgvw nvhhztv
# This is a encrypted message

09. Typoglycemia

"""
09. Typoglycemia

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


def generate_typoglycemia(words: list) -> list:
    res = []
    for word in words:
        if len(word) < 4:
            res.append(word)
        else:
            medium = "".join(random.sample(word[1:-1], k=len(word[1:-1])))  # method 1
            # medium = "".join(random.shuffle(list(word[1:-1])))  # method2
            res.append(word[0] + medium + word[-1])
    return res


s = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
res = generate_typoglycemia(s.split())
print(" ".join(res))
# I clo'undt beevile taht I cuold alulctay urtnneadsd waht I was reanidg : the pmheoenanl poewr of the human mind .

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?