LoginSignup
14
1 / 2

言語処理100本ノック2015
http://www.cl.ecei.tohoku.ac.jp/nlp100/

<この項は書きかけです。順次追記します。>

時々、作業の貼り付けで間違って上書きすることがあります。ごめんなさい。
結果として間違ったURLを指している場合など早急に訂正します。

「言語処理100本ノック2015」に今から乗り込むために、これまでの皆様の成果を確認させていただいています。

以下の5項目の洗い出しも合わせて行います。

  1. pythonで一番感激したプログラム(問題)(100本の中で)
    今回別の言語で記述したのであればその言語で。
    複数の言語が理解できる人は、他の言語との比較も書く。
  2. pythonを使っていて便利だなと思った瞬間(とその時の問題)。
    一番感激した次でも結構です。
  3. 自分の仕事で一番よく使いそうな処理を含む問題
  4. 自分の工夫が他より優れていると思う問題とその箇所(最悪のものとの比較でもよい)
  5. いまだによく理解できていない問題
    なお、100本の理解度を、1から100までつけてください。

引用に当たって、空白行は、空間の節約と比較のため詰めさせていただいています。ごめんなさい。ファイル名は、コマンドファイル作成上重複を避けるため変更させていただいています。ごめんなさい。参照URLは、処理の後ろに書いています。

ファイルだけで処理結果を示していない場合は、処理確認の記録をつけさせていただいています。処理がどうなるかを確認したという記録です。スクリプトとして確かめさせていただいていますが、見出しの分類はコマンドにしているかもしれません。

各設問について十人以上の答えを、いくつかに分類して、Pythonの機能理解を助けるための資料とさせてください。

どの答えが、設問の趣旨にあっているかという判定はしていません。設問された方の意図、裏の意図を推察できる段階にないためです。回答された方の意図も必ずしもうまく理解できているとは限りません。

最初の記述から、順に手直しされている方もお見えになります。
拡張性、類似の課題への考察を書かれている方もお見えになります。
コメントでの貴重な意見や、参考になるURL等の提示もあります。
ぜひ、URL先もご確認ください。

できるだけ最初の版がどういう発想から来ているかの種類を多く理解することをまず取り組んでいます。可読性、保守性、拡張性につていの検討が今後の課題です。

docker

dockerでanacondaを利用する場合は簡単です。

bash
$ docker run -it continuumio/anaconda3 /bin/bash

docker login
していないとエラーになるかもしれません。python3が利用できます。

演習

python3を前提とし、python2の回答はpython2と記載することにします。作業の中で、編集、複写で切り貼り間違いが多く、python2, python3の環境を利用するため別々のdockerを利用することにしました。

言語処理100本ノック 2015(python) 動作確認docker環境構築
https://qiita.com/kaizen_nagoya/items/abaf3fd0198f9f557243

ここで言う「落ち穂拾い」は、なるべくたくさんの成果を集めることにより、後学のためになることを目指しています。
一度に全てを網羅できないため、1ヶ月に1章づつ整理していく予定です。

名古屋で2018年7月から予定している「ゼロから作るDeep Learning 2自然言語処理編」の夕方のLTで毎月1章づつ取り上げる予定です。

目次

記法・課題の整理
第1章: 準備運動
00. 文字列の逆順

  1. 「パタトクカシーー」
  2. 「パトカー」+「タクシー」=「パタトクカシーー」
  3. 円周率
  4. 元素記号
  5. n-gram
  6. 集合
  7. テンプレートによる文生成
  8. 暗号文
  9. Typoglycemia

#記法・課題の整理

スクリプト

拡張子pyで保存。例えば、ここではmy.py。
pythonを打たずに実行したい場合は、先頭に

name.py
#! /usr/bin/env python

my.pyを直接実行できるようにするには、mac, linux等ではコマンドで

$ chmod +x name.py

と実行可能にしておく。
実行時は、カレントディレクトリにmy.pyがあるとすれば、

$ ./my.py

pythonと打たなくてよい。

コマンドで打った履歴のうち、間違えたものを除いて、ファイルにすれば、それがスクリプトファイルになる。

文字コード

文字コード指定は、

# -*- coding: utf-8 -*-
# coding: utf-8

など。

この指定がなくエラーになった例:

python2.7.0
$python py.py
SyntaxError: Non-ASCII character '\xe6' in file my.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

名前str

python3ではstr関数がある。@shiracamus
strを変数として利用すると混乱の元になる可能性がある。
python2ではstr属性がある。
変数としてstrは用いないのが良さそう。

教訓:関数名などの単語は変数として用いない。
(例外は例外として明示。)

python2とpython3

dockerで別々の動作確認環境を構築。

言語処理100本ノック 2015(python) 動作確認docker環境構築
https://qiita.com/kaizen_nagoya/items/abaf3fd0198f9f557243

関数の違い。
・printの書式の違い。
文字列の扱い。

#第1章: 準備運動

##00. 文字列の逆順
文字列"stressed"の文字を逆に(末尾から先頭に向かって)並べた文字列を得よ.

00用参考資料

ちょうど、まとめようと思った内容の記事があった。

Python リストの逆順
https://qiita.com/take333/items/b61e43c68751260689a6

00 コマンド1行

LangPro100-2015-00
>>> print("stressed"[::-1])
desserts

言語処理100本ノック 00〜09
https://qiita.com/nubilum/items/af0a2ff057b9a6d708ad

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

Python初心者が少しずつ言語処理100本ノックを頑張るエントリー
https://qiita.com/hbkr/items/64ac81a84ddfe93641fc

言語処理100本ノック第1章 by Python
https://qiita.com/yasuhitotanaka/items/d6fefa05d7d843ff8d16

00コマンド3行 python2.7

py00.py
str = "stressed"
str = str[::-1]
print str
$ python py00.py 
desserts

文系エンジニアが言語処理100本ノックやってみた in Python 00
https://qiita.com/4211111almomd/items/f4ba806eabe6d1f45905

00スクリプトファイル2行

00knock.py
s="stressed"
print(s[::-1])
python
$ python 00knock.py
desserts

言語処理100本ノック00
https://qiita.com/aira002/items/1a1ad7efd451a72e28c2

Python初心者が言語処理100本ノック2015をやってみた(00~04)
https://qiita.com/harusora/items/ffdd22262c972c402795

Pythonで言語処理100本ノック2015 問題00
https://qiita.com/Yuki-Takao/items/a1cd8331c341de48b6af

言語処理100本ノック 第1章 in Python
https://qiita.com/raahii/items/eb72b496669f541055c3

00スクリプトファイル、問題文字列表示機能付き

000.py
msg="stressed"
print(msg)
print(msg[::-1])
python
$ python 000.py
stressed
desserts

【python】100本ノックにチャレンジ!(000〜005)
https://qiita.com/masassy/items/6e25c0adc4ef7c8bf4fc

###00スクリプトファイル, coding付き

main.py
# coding: utf-8
target = u'stressed'
result = target[::-1]
print(result)
python
$ python main.py
desserts

素人の言語処理100本ノック:00
https://qiita.com/segavvy/items/709c6e2d156b7837b3a8

言語処理100本ノック 第1章 in Python
https://qiita.com/kimopyon/items/3884c90a04ae01eaacef

00スクリプトファイル: coding, python付き

00.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 00.py

str = "stressed"
print(str[-1::-1])
python
$ ./00.py
desserts
$ python 00.py
desserts

言語処理100本ノック with Python(第1章)
https://qiita.com/gamma1129/items/37bf660cf4e4b21d4267

00参考:プログラミング言語風1 join, insert

knock000.py
s = "stressed"
def reverse(s: str) -> str:
    list = []
    for char in s:
        list.insert(0, char)
    return "".join(list)
print(reverse(s))

Python で言語処理100本ノック2015
https://qiita.com/tanaka0325/items/08831b96b684d7ecb2f7

00参考:プログラミング言語風2,python2, len, xrange

python2
text = "stressed"
text_reverse = ""
n = len(text)
for i in xrange(n):
    text_reverse += text[n-i-1]
print text_reverse
#>>> desserts

「言語処理100本ノック 2015」ではじめるPythonとNLPスキルのリハビリテーション(第1章)
https://qiita.com/kazuhirokomoda/items/b113799b66090ac58204

###00参考:プログラミング言語風3 range, len

word = "stressed"
invword = ""
for k in range(len(word)):
    invword = invword + str(word[len(word)-(k+1)])
print(invword)

言語処理100本ノック 第1章: 準備運動 やってみた
https://qiita.com/mas03151997/items/110ac3a1f99a2a397026

00参考:プログラミング言語風4 range,len

nlp00.py
#!/usr/bin/env python
s = 'stressed'
def reverse(a):
    for i in range(len(a)/2):
       temp = a[i]
       a[i] = a[len(a)-(i+1)]
       a[len(a)-(i+1)] = a[i]
    return a
print(reverse(s))

言語処理100本ノック 00~02
https://qiita.com/gita/items/c4308e731132814bdb31

00コマンド2行 python2.7.1

python200.py
# coding: utf-8
word = "stressed"
print word[::-1] #文字列の後ろからスライス
$ python python200.py 
desserts

言語処理100本ノック 2015 第1章: 準備運動(Python)
https://qiita.com/Miggy/items/4459f5ef043a9c294bb3

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

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

01コマンド1行

print("パタトクカシーー"[0:-1:2])

言語処理100本ノック 00〜09
https://qiita.com/nubilum/items/af0a2ff057b9a6d708ad

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

01コマンド2行:python2

pyhon2
>>> word = u"パタトクカシーー"
>>>print word[::2]
パトカー
>>>

言語処理100本ノック 2015 第1章: 準備運動(Python)
https://qiita.com/Miggy/items/4459f5ef043a9c294bb3

言語処理100本ノック 第1章: 準備運動 やってみた
https://qiita.com/mas03151997/items/110ac3a1f99a2a397026

コマンド3行:配列固定偶数:python2

python2
>>>text = u"パタトクカシーー"
>>>text_concat = text[0] + text[2] + text[4] + text[6]
>>>print text_concat
 パトカー
>>>

「言語処理100本ノック 2015」ではじめるPythonとNLPスキルのリハビリテーション(第1章)
https://qiita.com/kazuhirokomoda/items/b113799b66090ac58204

01スクリプト

001.py
s = "パタトクカシーー"
print(s[::2])

Python初心者が少しずつ言語処理100本ノックを頑張るエントリー
https://qiita.com/hbkr/items/64ac81a84ddfe93641fc

Python初心者が言語処理100本ノック2015をやってみた(00~04)
https://qiita.com/harusora/items/ffdd22262c972c402795

言語処理100本ノック01
https://qiita.com/aira002/items/2d5be2cd145500162221

Pythonで言語処理100本ノック2015 問題01
https://qiita.com/Yuki-Takao/items/05a230c264b2136ec3af

言語処理100本ノック 第1章 in Python
https://qiita.com/raahii/items/eb72b496669f541055c3

01スクリプト  len

nlp01.py
#coding: UTF-8
str = u'パタトクカシーー'
print(str[0:len(str):2])

言語処理100本ノック 00~02
https://qiita.com/gita/items/c4308e731132814bdb31

###01スクリプト 配列固定奇数

q01='パタトクカシーー'
#print(q01[1]+q01[3]+q01[5]+q01[7])

言語処理100本ノック第1章 by Python
https://qiita.com/yasuhitotanaka/items/d6fefa05d7d843ff8d16

言語処理100本ノック 第1章 in Python
https://qiita.com/raahii/items/eb72b496669f541055c3

01スクリプト 配列固定偶数

knock001.py
s = "パタトクカシーー"
print(s[0] + s[2] + s[4] + s[6])

Python で言語処理100本ノック2015
https://qiita.com/tanaka0325/items/08831b96b684d7ecb2f7

01スクリプト str

01.py
str = u"パタトクカシーー"
print (str[::2])

文系エンジニアが言語処理100本ノックやってみた in Python 01
https://qiita.com/4211111almomd/items/de1a6c87efca639bfcf9

知見:str関数が利用できなくなる。@shiracamus

01スクリプト str, python, coding付き

01.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 01.py
str = u'パタトクカシーー'
print(str[0::2])

言語処理100本ノック with Python(第1章)
https://qiita.com/gamma1129/items/37bf660cf4e4b21d4267

01スクリプト:python2

main01.py(python2.7)
# coding: utf-8
target = u'パタトクカシーー'
result = target[::2]
print(result)
$ python main01.py
パトカー

素人の言語処理100本ノック:01
https://qiita.com/segavvy/items/966c7b658ca740f6164b

01スクリプト:問題文字列表示機能付き

001.py
msg  = "パタトクカシーー"
print(msg)
msg_find = msg[::2]
print(msg_find)

【python】100本ノックにチャレンジ!(000〜005)
https://qiita.com/masassy/items/6e25c0adc4ef7c8bf4fc

01スクリプト:coding付き

# coding: utf-8
word = "パタトクカシーー"
new_word = word[::2]
print(new_word)

言語処理100本ノック 第1章 in Python
https://qiita.com/kimopyon/items/3884c90a04ae01eaacef

素人の言語処理100本ノック:01
https://qiita.com/segavvy/items/966c7b658ca740f6164b

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

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

02スクリプト1行

print("".join(a+b for a, b in zip("パトカー", "タクシー")))

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

02スクリプト, join, zip

002.py
s = "".join(i+j for i, j in zip("パトカー", "タクシー"))
print(s)

Python初心者が少しずつ言語処理100本ノックを頑張るエントリー
https://qiita.com/hbkr/items/64ac81a84ddfe93641fc

02スクリプト, join, zip pyhon2.

python2
# coding: utf-8
word1 = u"パトカー"
word2 = u"タクシー"
joined_word = [x + y for x , y in zip(word1, word2)]
print ''.join(joined_word)
$ python py01a.py
パタトクカシーー

02スクリプト, class, string, self, char, index, def, at, concat...

02.py
class String(str):
    def __init__(self, char):
        self._char = char
    def at(self, index):
        if index >= len(self._char):
            return ''
        return self._char[index]
def concat(a, b):
    a = String(a)
    b = String(b)
    max_len = max(len(a), len(b))
    return ''.join([a[i] + b[i] for i in range(max_len)])
print(concat("パトカー", "タクシー"))
$ python 02.py
パタトクカシーー

言語処理100本ノック 00〜09
https://qiita.com/nubilum/items/af0a2ff057b9a6d708ad

02スクリプト, python, coding, range, len

nlp02.py
#!/usr/bin/env python
#coding: UTF-8
str1 = u'パトカー'
str2 = u'タクシー'
str = ''
for i in range(len(str1)):
    str = str + str1[i]+str2[i]
print(str)

言語処理100本ノック 00~02
https://qiita.com/gita/items/c4308e731132814bdb31

02スクリプト range, len, python2

02.py
# coding: utf-8
a = u"パトカー"
b = u"タクシー"
c = ""
for i in range(len(a)):
    c = (c + a[i] +b[i])
print c

02スクリプト, range

02knock.py
s="パトカー"
v="タクシー"
for i in range(1,5):
    print (s[i-1:i]+v[i-1:i],end="")

言語処理100本ノック02
https://qiita.com/aira002/items/d0854bfc22a032e9526c

###02スクリプト, zip

02.py
s = ""
for i,j in zip("パトカー", "タクシー"):
    s += i+j
print(s)

Python初心者が言語処理100本ノック2015をやってみた(00~04)
https://qiita.com/harusora/items/ffdd22262c972c402795

02スクリプト, zip

Python3
s1 = 'パトカー'
s2 = 'タクシー'
ans = ''
for i,j in zip(s1,s2):
    ans +=  i + j
print(ans)

Pythonで言語処理100本ノック2015 問題02
https://qiita.com/Yuki-Takao/items/798434d947a4c1fc185e

###02スクリプト, coding, zip, ()ありfor

main.py
# coding: utf-8
target1 = 'パトカー'
target2 = 'タクシー'
result = ''
for (a, b) in zip(target1, target2):
    result += a + b
print(result)

素人の言語処理100本ノック:02
https://qiita.com/segavvy/items/725b20f21951975a06fd

02スクリプト, coding, zip,()なしfor,

# cording utf-8
word1 = u"パトカー"
word2 = u"タクシー"
mix_word = ""
for w1,w2 in zip (word1,word2):
    mix_word += w1 + w2
print(mix_word)

言語処理100本ノック 第1章 in Python
https://qiita.com/kimopyon/items/3884c90a04ae01eaacef

02スクリプト, python, coding, zip, ()なしfor python2

02c.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 02.py
str1 = u'パトカー'
str2 = u'タクシー'
str3 = u''
for a,b in zip(str1, str2):
    str3 = str3 + a + b
print str3
$ python 02c.py
パタトクカシーー

言語処理100本ノック with Python(第1章)
https://qiita.com/gamma1129/items/37bf660cf4e4b21d4267

02スクリプト, join, zip

02.py
word1="パトカー"
word2="タクシー"
ans="".join([c1+c2 for c1,c2 in zip(word1,word2)])
print(ans)

言語処理100本ノック 第1章 in Python
https://qiita.com/raahii/items/eb72b496669f541055c3

02スクリプト len, range()

knock002.py
s1 = "パトカー"
s2 = "タクシー"
s3 = ""
for i in range(len(s1)):
    s3 = s3 + s1[i] + s2[i]
print(s3)

Python で言語処理100本ノック2015
https://qiita.com/tanaka0325/items/08831b96b684d7ecb2f7

言語処理100本ノック 第1章: 準備運動 やってみた
https://qiita.com/mas03151997/items/110ac3a1f99a2a397026

02スクリプト, len, range, python, coding

nlp02.py
#!/usr/bin/env python
#coding: UTF-8
str1 = u'パトカー'
str2 = u'タクシー'
str = ''
for i in range(len(str1)):
    str = str + str1[i]+str2[i]
print(str)

02スクリプト len, range(0,)

002.py
msg1 = "パトカー"
msg2= "タクシー"
msg_add=''
for i in range(0,len(msg1)):
    msg_add += msg1[i]
    msg_add += msg2[i]
print(msg_add)

【python】100本ノックにチャレンジ!(000〜005)
https://qiita.com/masassy/items/6e25c0adc4ef7c8bf4fc

02スクリプト min, len, range

q021='パトカー'
q022='タクシー'
length=min(len(q021),len(q022))
ansq02=''
for i in range(length):
    temp=q021[i]+q022[i]
    ansq02+=temp
print(ansq02)

言語処理100本ノック第1章 by Python
https://qiita.com/yasuhitotanaka/items/d6fefa05d7d843ff8d16

02スクリプト, python2, len, xrange

text1 = u"パトカー"
text2 = u"タクシー"
text_concat = ""
m = len(text1)
n = len(text2)
for i in xrange(m):
    if i<n:
        text_concat += text1[i] + text2[i]
        if i == m-1:
            text_concat += text2[i+1:]
    else:
        text_concat += text1[i:]
        break
print text_concat
#>>> パタトクカシーー

「言語処理100本ノック 2015」ではじめるPythonとNLPスキルのリハビリテーション(第1章)
https://qiita.com/kazuhirokomoda/items/b113799b66090ac58204

03. 円周率

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

03コマンド2行、カンマ出力

03sentence.py
sentence = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
print([len(word.rstrip(".,")) for word in sentence.split()])
$ python 03sentece.py 
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

03コマンド、出力例

sentence = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
word_length = [len(x.strip(',.')) for x in sentence.split()]
print word_length
#>>> [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

「言語処理100本ノック 2015」ではじめるPythonとNLPスキルのリハビリテーション(第1章)
https://qiita.com/kazuhirokomoda/items/b113799b66090ac58204

03スクリプト、カンマ出力

03knock.py
from collections import Counter
st="Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
words=st.replace(",","").replace(".","").split()
list=[]
for i in words:
    k=len(i)
    list.append(k)
print (list)
python
$ python 03knock.py 
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

言語処理100本ノック03
https://qiita.com/aira002/items/8f2355769df1cf3654e8

03スクリプト,for split, strip

03.py
s = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
count_list = []
for i in s.split():
    count_list.append(len(i.strip(",.")))
print(count_list)
python 03b.py
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

Python初心者が言語処理100本ノック2015をやってみた(00~04)
https://qiita.com/harusora/items/ffdd22262c972c402795

03スクリプト,3行, strip, for, split

03.py
s = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
count = [len(i.strip(",.")) for i in s.split()]
print(count)
$ python 03.py
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

Python初心者が少しずつ言語処理100本ノックを頑張るエントリー
https://qiita.com/hbkr/items/64ac81a84ddfe93641fc

言語処理100本ノック第1章 by Python
https://qiita.com/yasuhitotanaka/items/d6fefa05d7d843ff8d16

言語処理100本ノック 第1章 in Python
https://qiita.com/raahii/items/eb72b496669f541055c3

03スクリプト,split, len, strip,for

slsf03.py
word = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
word_list = word.split(" ")
count = [len(word_temp.strip(",.")) for word_temp in word_list]
print(count)
$ python slsf03.py 
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

言語処理100本ノック 第1章: 準備運動 やってみた
https://qiita.com/mas03151997/items/110ac3a1f99a2a397026

03スクリプト

py03.py
s = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
words = s.split(" ")
char_count = []
for word in words:
    char_count.append(len(word))
print(char_count)
$ python py03.py 
[3, 1, 4, 1, 6, 9, 2, 7, 5, 3, 5, 8, 9, 7, 10]

Python で言語処理100本ノック2015
https://qiita.com/tanaka0325/items/08831b96b684d7ecb2f7

03スクリプト, translate, maketrans, split, len, append

words = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
result = []
new_words = words.translate(str.maketrans("","",",."))
for word in new_words.split(' '):
    word_length = len(word)
    result.append(word_length)
print(result)

言語処理100本ノック 第1章 in Python
https://qiita.com/kimopyon/items/3884c90a04ae01eaacef

###03スクリプト,coding, split, len, count,

main03.py
# coding: utf-8
target = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.'
result = []
words = target.split(' ')
for word in words:
    result.append(len(word) - word.count(',') - word.count('.'))
print(result)
$ python main03.py
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

素人の言語処理100本ノック:03
https://qiita.com/segavvy/items/a0ddefb64cc878b9639b

03スクリプト,def,len,strip,join,for,str

def get_word_length(word):
    word = word.strip(",.")
    return len(word)
pieces = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.".split(" ")
print("".join([str(get_word_length(c)) for c in pieces]))
$ python 03def.py 
314159265358979

言語処理100本ノック 00〜09
https://qiita.com/nubilum/items/af0a2ff057b9a6d708ad

03スクリプト,replace, split,append,len

python303.py
s = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
s = s.replace(',', '').replace('.','')
s_list = s.split()
answer = []
#文字数をカウントし出現順に配列に格納してるとこ
for n in s_list:
    answer.append(len(n))
print(answer)
$ python python303.py
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

Pythonで言語処理100本ノック2015 問題03
https://qiita.com/Yuki-Takao/items/22943edb52cac293fa18

03スクリプト, map,len,split,range,append

nlp03.py
#! usr/bin/env python
from collections import Counter 
str = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics'
li = []
count = Counter(map(len,str.split())).most_common()
for i in range(len(count)):
    li.append(count[i][0])
print(li)
$ python nlp03.py 
[9, 3, 1, 7, 5, 4, 6, 2, 8]

言語処理100本ノック 03 ~ 05
https://qiita.com/gita/items/019148ac07716c82a9f1

03スクリプト, coding, strip, append,

word2list_003.py
# -*- coding: utf-8 -*-
def word2list(msg):
    temp_msg = ''
    list = []
    for temp in msg:
        temp=temp.rstrip(",.")
        if(temp==' '):
            list.append(temp_msg)
            temp_msg=''
        else:
            temp_msg += temp
    list.append(temp_msg)
    return list
if __name__ == "__main__":
    msg = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
    list = []
    num_list = []
    temp = ''
    list = word2list(msg)
    for num in list:
        num_list.append(len(num))
    print(num_list)
$ python word2list_003.py 
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]

【python】100本ノックにチャレンジ!(000〜005)
https://qiita.com/masassy/items/6e25c0adc4ef7c8bf4fc

###03スクリプト:python2

03text.py
text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
text = text.translate(None, ".,") #「.」「,」を削除。
text = text.split() #str.split()は、デフォルトで空白で切り分け
num_char = [len(x) for x in text]
print text
print num_char

言語処理100本ノック 2015 第1章: 準備運動(Python)
https://qiita.com/Miggy/items/4459f5ef043a9c294bb3

03スクリプト, python2,coding, replace, split, append, len

python203.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 03.py
str = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
str = str.replace('.', "")
str = str.replace(',', "")
str = str.split()
list = []
for word in str:
    list.append(len(word))
print list

言語処理100本ノック with Python(第1章)
https://qiita.com/gamma1129/items/37bf660cf4e4b21d4267

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

004.py
s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
dic = {word[:2-(i in (1,5,6,7,8,9,15,16,19))]:i for i, word in enumerate(s.replace(".", "").split(), 1)}
print(dic)
# python 04text.py 
[('H', 1), ('He', 2), ('Li', 3), ('Be', 4), ('B', 5), ('C', 6), ('N', 7), ('O', 8), ('F', 9), ('Ne', 10), ('Na', 11), ('Mi', 12), ('Al', 13), ('Si', 14), ('P', 15), ('S', 16), ('Cl', 17), ('Ar', 18), ('K', 19), ('Ca', 20)]

Python初心者が少しずつ言語処理100本ノックを頑張るエントリー
https://qiita.com/hbkr/items/64ac81a84ddfe93641fc

04コマンド, enumerate,split

py04split.py
sentence = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
numbers = [1, 5, 6, 7, 8, 9, 15, 16, 19]
print({(word[0] if i in numbers else word[:2]):i for i, word in enumerate(sentence.split(), 1)})
$ python py04split.py 
{'H': 1, 'He': 2, 'Li': 3, 'Be': 4, 'B': 5, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Ne': 10, 'Na': 11, 'Mi': 12, 'Al': 13, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17, 'Ar': 18, 'K': 19, 'Ca': 20}

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

04コマンド, enumerate, update

04.py
s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
dict = {}
for (i, w) in enumerate(s.replace(".", "").split(), 1):
    if i in (1,5,6,7,8,9,15,16,19):
        dict.update({w[0]:i})
    else:
        dict.update({w[:2]:i})
print(dict)
python 04.py
{'Be': 4, 'C': 6, 'B': 5, 'Ca': 20, 'F': 9, 'S': 16, 'H': 1, 'K': 19, 'Al': 13, 'Mi': 12, 'Ne': 10, 'O': 8, 'N': 7, 'P': 15, 'Si': 14, 'Ar': 18, 'Na': 11, 'Li': 3, 'Cl': 17, 'He': 2}

Python初心者が言語処理100本ノック2015をやってみた(00~04)
https://qiita.com/harusora/items/ffdd22262c972c402795

04スクリプト, def, index, range, len

py04def.py
def get_atomic_symbol(index, word):
    if (index + 1) in [1, 5, 6, 7, 8, 9, 15, 16, 19]:
        return word[0:1]
    return word[0:2]
pieces = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.".split()
symbol_map = { i:get_atomic_symbol(i, pieces[i]) for i in range(len(pieces)) }
print(symbol_map)
$ python py04def.py
{0: 'H', 1: 'He', 2: 'Li', 3: 'Be', 4: 'B', 5: 'C', 6: 'N', 7: 'O', 8: 'F', 9: 'Ne', 10: 'Na', 11: 'Mi', 12: 'Al', 13: 'Si', 14: 'P', 15: 'S', 16: 'Cl', 17: 'Ar', 18: 'K', 19: 'Ca'}

言語処理100本ノック 00〜09
https://qiita.com/nubilum/items/af0a2ff057b9a6d708ad

04スクリプト, strip, split, for, enumerate, if, else

q04.py
q04="Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
dict={}
q04_list=[(i.strip(",.")) for i in q04.split()]
print(q04_list)
q04_listNum=[1, 5, 6, 7, 8, 9, 15, 16, 19]
for idx,val in enumerate(q04_list):
    temp_char=val
    idx += 1
    if ((idx) in q04_listNum):
        dict[temp_char[0]] = idx
    else:
        dict[temp_char[:2:1]] =idx
print(dict)
# python q04.py
['Hi', 'He', 'Lied', 'Because', 'Boron', 'Could', 'Not', 'Oxidize', 'Fluorine', 'New', 'Nations', 'Might', 'Also', 'Sign', 'Peace', 'Security', 'Clause', 'Arthur', 'King', 'Can']
{'Be': 4, 'C': 6, 'B': 5, 'Ca': 20, 'F': 9, 'S': 16, 'H': 1, 'K': 19, 'Al': 13, 'Mi': 12, 'Ne': 10, 'O': 8, 'Li': 3, 'P': 15, 'Si': 14, 'Ar': 18, 'Na': 11, 'N': 7, 'Cl': 17, 'He': 2}

言語処理100本ノック第1章 by Python
https://qiita.com/yasuhitotanaka/items/d6fefa05d7d843ff8d16

04コマンド, strip, for, split, enumerate, update, length

se04.py
# coding: utf-8
sentence ="Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
#単語に分解
words=[word.strip(".,") for word in sentence.split()]
#先頭の1文字(または2文字)と、その単語のインデックスを対応付ける辞書を作成
link={}
for i,v in enumerate(words,1):
    length=1 if i in [1,5,6,7,8,9,15,16,19] else 2
    link.update({v[:length]:i})
print(link)
# python se04.py
{'Be': 4, 'C': 6, 'B': 5, 'Ca': 20, 'F': 9, 'S': 16, 'H': 1, 'K': 19, 'Al': 13, 'Mi': 12, 'Ne': 10, 'O': 8, 'N': 7, 'P': 15, 'Si': 14, 'Ar': 18, 'Na': 11, 'Li': 3, 'Cl': 17, 'He': 2}

言語処理100本ノック 第1章 in Python
https://qiita.com/raahii/items/eb72b496669f541055c3

04コマンド enumerate

04knock.py
st0="Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
words=st0.split()
i=0
for (i,x) in enumerate(words):
 if i==0 or i==4 or i==5 or i==6 or i==7 or i==8 or i==14 or i==15 or i==18:
  print(i,x[0:1])
 else:
  print(i,x[0:2])

出力が1文字か2文字か改行があると一目瞭然。

# python 04knock.py 
(0, 'H')
(1, 'He')
(2, 'Li')
(3, 'Be')
(4, 'B')
(5, 'C')
(6, 'N')
(7, 'O')
(8, 'F')
(9, 'Ne')
(10, 'Na')
(11, 'Mi')
(12, 'Al')
(13, 'Si')
(14, 'P')
(15, 'S')
(16, 'Cl')
(17, 'Ar')
(18, 'K')
(19, 'Ca')

言語処理100本ノック04
https://qiita.com/aira002/items/e8eb2fff0f17b341a6ca

04コマンド, split, 配列

p04.py
# coding: utf-8
"""
戦略
・条件指定されたナンバーのリストを定義し、分岐判定に使う
"""
s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Mght Also Sign Peace Security Clause. Arthur King Can."
s_list = s.split()
condition_list = [1, 5, 6, 7, 8, 9, 15, 16, 19]
answer = {}
i = 0
#文字数をカウントし出現順に配列に格納する
for n in s_list:
    i += 1
    if i in condition_list:
        answer[n[:1]] = (i)
    else:
        answer[n[:2]] = (i)
print(answer)
# python p04.py
{'S': 16, 'Be': 4, 'C': 6, 'B': 5, 'Ca': 20, 'F': 9, 'Mg': 12, 'H': 1, 'K': 19, 'Al': 13, 'Ne': 10, 'O': 8, 'Li': 3, 'P': 15, 'Si': 14, 'Ar': 18, 'Na': 11, 'N': 7, 'Cl': 17, 'He': 2}

Pythonで言語処理100本ノック2015 問題04
https://qiita.com/Yuki-Takao/items/d18decf3b8d96cc7cab6

###04コマンド,def, for, if, 配列

word2dict_004.py
def word2dict(msg):
    temp = ''
    temp_msg = ''
    temp_list=[]
    i = 1
    for temp in msg:
        if(temp==' ' or temp=='. '):
            temp_list.append((i, temp_msg))
            temp_msg = ''
            i = i + 1
        else:
            temp_msg+=temp
    temp_list.append((i,temp_msg))
    return  temp_list
if __name__=="__main__":
    msg = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
    dic = {}
    temp_list = []
    temp_list = word2dict(msg)
    for key,item in temp_list:
        if(key==1 or key == 5 or key == 6 or key == 7or key == 8or key == 9or key == 15or key == 16or key == 19):
            dic[key]=item[:1]
        else:
            dic[key]=item[:2]
    print(dic)
# python word2dict_004.py 
{1: 'H', 2: 'He', 3: 'Li', 4: 'Be', 5: 'B', 6: 'C', 7: 'N', 8: 'O', 9: 'F', 10: 'Ne', 11: 'Na', 12: 'Mi', 13: 'Al', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar', 19: 'K', 20: 'Ca'}

【python】100本ノックにチャレンジ!(000〜005)
https://qiita.com/masassy/items/6e25c0adc4ef7c8bf4fc

04コマンド, split, for, enumerate, if, else

main04.py
# coding: utf-8
num_first_only = (1, 5, 6, 7, 8, 9, 15, 16, 19)
target = 'Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'
result = {}
words = target.split(' ')
for (num, word) in enumerate(words, 1):
    if num in num_first_only:
        result[word[0:1]] = num
    else:
        result[word[0:2]] = num
print(result)
 python main04.py 
{'Be': 4, 'C': 6, 'B': 5, 'Ca': 20, 'F': 9, 'S': 16, 'H': 1, 'K': 19, 'Al': 13, 'Mi': 12, 'Ne': 10, 'O': 8, 'Li': 3, 'P': 15, 'Si': 14, 'Ar': 18, 'Na': 11, 'N': 7, 'Cl': 17, 'He': 2}

04コマンドpython2

04text.py
# coding: utf-8
text = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
text = text.translate(None, ".,") 
text = text.split() 
pos_dict = {}
for i, x in enumerate(text, start=1):
    if i in [1, 5, 6, 7, 8, 9, 15, 16, 19]:
        pos_dict[x[:1]] = i
    else:
        pos_dict[x[:2]] = i
# 辞書の中身を出現順にソートして表示 cf.http://qiita.com/xxthermidorxx/items/b546471c37b2f443f4c7
print sorted(pos_dict.items(), key=lambda x:x[1])
# python 04text.py 
[('H', 1), ('He', 2), ('Li', 3), ('Be', 4), ('B', 5), ('C', 6), ('N', 7), ('O', 8), ('F', 9), ('Ne', 10), ('Na', 11), ('Mi', 12), ('Al', 13), ('Si', 14), ('P', 15), ('S', 16), ('Cl', 17), ('Ar', 18), ('K', 19), ('Ca', 20)]

言語処理100本ノック 2015 第1章: 準備運動(Python)
https://qiita.com/Miggy/items/4459f5ef043a9c294bb3

05. n-gram

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

05スクリプト, lambda, join, split, range, len, for

lam05.py
word_bigram = lambda sentence: ["-".join(sentence.split()[i:i+2]) for i in range(len(sentence.split())-1)]
letter_bigram = lambda sentence: [word[i:i+2] for word in sentence.split() for i in range(len(word)-1)]
sentence = "I am an NLPer"
print(word_bigram(sentence))
print(letter_bigram(sentence))
# python lam05.py 
['I-am', 'am-an', 'an-NLPer']
['am', 'an', 'NL', 'LP', 'Pe', 'er']

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

05スクリプト, def, tuple, for, strip, split

005.py
def n_gram(s, n): return {tuple(s[i:i+n]) for i in range(len(s)-n+1)}
s = "I am an NLPer"
print(n_gram(s, 2))
print(n_gram([t.strip(".,") for t in s.split()], 2))
# python 005.py
set([('N', 'L'), ('m', ' '), ('e', 'r'), ('a', 'n'), ('I', ' '), ('n', ' '), ('L', 'P'), (' ', 'N'), (' ', 'a'), ('a', 'm'), ('P', 'e')])
set([('am', 'an'), ('an', 'NLPer'), ('I', 'am')])

Python初心者が少しずつ言語処理100本ノックを頑張るエントリー
https://qiita.com/hbkr/items/64ac81a84ddfe93641fc

05スクリプト, for, range, len, strip, split

q05.py
q05="I am an NLPer"
# bi-gram for char
char_bigram=[q05[i:i+2] for i in range(len(q05)-1)]
print(char_bigram)
# n-bigram for words
words=[(i.strip(".,")) for i in q05.split()]
words_bigram=["-".join(words[i:i+2]) for i in range(len(words)-1)]
print(words_bigram)
# python q05.py
['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']
['I-am', 'am-an', 'an-NLPer']

言語処理100本ノック第1章 by Python
https://qiita.com/yasuhitotanaka/items/d6fefa05d7d843ff8d16

05スクリプト,def, for, range, append

def05.py
def ngram(target, n):
    ngram = []
    for i in range(len(target) - n + 1):
        ngram.append(target[i:(i + n)])
    return ngram
print(ngram("I am an NLPer", 2))
print(ngram(["I", "am", "an", "NLPer"], 2))
# python def05.py 
['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']
[['I', 'am'], ['am', 'an'], ['an', 'NLPer']]

言語処理100本ノック 00〜09
https://qiita.com/nubilum/items/af0a2ff057b9a6d708ad

05スクリプト

s05.py
# coding: utf-8
sentence="I am an NLPer"
#文字bi-gram
charGram=[sentence[i:i+2] for i in range(len(sentence)-1)]
#単語bi-gram
words=[word.strip(".,") for word in sentence.split()] 
wordGram=["-".join(words[i:i+2]) for i in range(len(words)-1)]
print(charGram)
print(wordGram)
# python s05.py
['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']
['I-am', 'am-an', 'an-NLPer']

言語処理100本ノック 第1章 in Python
https://qiita.com/raahii/items/eb72b496669f541055c3

###05スクリプト,def, join,split,for,range,len

d05.py
def word_ngram(seq, n):
    return ["-".join(seq.split()[i:i+n]) for i in range(len(seq.split())-n+1)]
def char_ngram(seq, n):
    return ["".join(seq[i:i+n]) for i in range(len(seq)-n+1)]
def main():
    seq = "I am an NLPer"
    word_2gram_list, char_2gram_list = word_ngram(seq, 2), char_ngram(seq, 2)
    print(word_2gram_list)
    print(char_2gram_list)
if __name__ == '__main__':
    main()
# python d05.py
['I-am', 'am-an', 'an-NLPer']
['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']

Python初心者が言語処理100本ノック2015をやってみた(05~09)
https://qiita.com/harusora/items/a8218695c2a756af67c7

05コマンド

main05.py
# coding: utf-8
def n_gram(target, n):
    '''指定されたリストからn-gramを作成
    引数:
    target -- 対象リスト
    n -- n-gramのn値(1ならuni-gram、2ならbi-gram...)
    戻り値:
    gramのリスト
    '''
    result = []
    for i in range(0, len(target) - n + 1):
        result.append(target[i:i + n])
    return result
target = 'I am an NLPer'
words_target = target.split(' ')
# 単語bi-gram
result = n_gram(words_target, 2)
print(result)
# 文字bi-gram
result = n_gram(target, 2)
print(result)
# python main05.py
[['I', 'am'], ['am', 'an'], ['an', 'NLPer']]
['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']

素人の言語処理100本ノック:05
https://qiita.com/segavvy/items/6f9f028914176c069c41

05コマンド

re05.py
# coding: utf-8
import re
sentence_string = "I am an NLPer"
sentence_list = sentence_string.split()
def n_gram(sequence,n):
    u"""文字列で渡されたとき文字bi-gram,リストとして渡されたとき単語bi-gramとして扱われる。
    """
    result = []
    if isinstance(sequence,str):
        sequence = list(re.sub("[,. ]","",sequence))
    for i in range(len(sequence)- n+1):
        result.append('-'.join(sequence[i:i+n]))        
    return result
print(n_gram(sentence_string,2))
print(n_gram(sentence_list,2))
# python re05.py
['I-a', 'a-m', 'm-a', 'a-n', 'n-N', 'N-L', 'L-P', 'P-e', 'e-r']
['I-am', 'am-an', 'an-NLPer']

言語処理100本ノック 第1章 in Python
https://qiita.com/kimopyon/items/3884c90a04ae01eaacef

###05コマンド, shell, coding, def, ...

o05.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 05.py
original = "I am an NLPer"
def ngram(input, n):
    # 文字 n-gram (引数 str)
    l = len(input)
    if type(input) == str:
        input = "$" * (n - 1) + input + "$" * (n - 1)
        for i in xrange(l + 1):
            print input[i:i+n]
    # 単語 n-gram (引数 list)
    elif type(input) == list:
        input = ["$"] * (n - 1) + input + ["$"] * (n - 1)
        for i in xrange(l + 1):
            print input[i:i+n]
ngram(original, 2)              # 文字 n-gram
original = original.split()
ngram(original, 2)              # 単語 n-gram
# ./o05.py
$I
I 
 a
am
m 
 a
an
n 
 N
NL
LP
Pe
er
r$
['$', 'I']
['I', 'am']
['am', 'an']
['an', 'NLPer']
['NLPer', '$']

言語処理100本ノック with Python(第1章)
https://qiita.com/gamma1129/items/37bf660cf4e4b21d4267

05コマンド, from, import, def,...

ngram_005.py
# coding: utf-8
from training.word2list_003 import word2list
def ngram(msg,N,type):
    if(type=='word'):
        bigram_word=''
        bigram_list=[]
        temp_list=word2list(msg)
        i=0
        while(i < int(len(temp_list))-1):
#temp_listからNで指定した数のrangeを設定した単語数を取得してword_listへ代入
            word_list = temp_list[i:(N+i)]
            for word in word_list:
                bigram_word += word
                continue
            bigram_list.append(bigram_word)
            bigram_word =''
            i +=1
        return bigram_list
    elif(type=='char'):
        temp_char_list=[]
        temp_bigram_list=[]
        bigram_char = ''
        bigram_list = []
        for temp_char in msg:
            if(temp_char==' ' or temp_char==','):
                continue
            else:
                temp_char_list.append(temp_char)
            continue
        i=0
#temp_listからNで指定した数のrangeを設定した文字数を取得してword_listへ代入
        while(i<int(len(temp_char_list))-1):
            temp_bigram_list=temp_char_list[i:(N+i)]
            for char in temp_bigram_list:
                bigram_char += char
                continue
            bigram_list.append(bigram_char)
            bigram_char=''
            i+=1
            continue
        return bigram_list
if __name__ == "__main__":
        msg = "I am an NLPer"
        N=2
        type='char'
#       type='word'
        bigram_list = ngram(msg,N,type)
        print(bigram_list)

from training.word2list_003 import word2list ファイルを作成中。
【python】100本ノックにチャレンジ!(000〜005)
https://qiita.com/masassy/items/6e25c0adc4ef7c8bf4fc

06. 集合

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

【python】100本ノックにチャレンジ!(006〜009)
https://qiita.com/masassy/items/4bd0b901e2fa5b43dd48

from training.bigram_005 import ngram

msg1 = "paraparaparadise"
msg2 = "paragraph"
msg3 = "se"

type = 'char'
X_list = ngram(msg1,2,type)
Y_list = ngram(msg2,2,type)
msg3_list = ngram(msg3,2,type)

set_X=set(X_list)
set_Y=set(Y_list)
set_msg3=set(msg3_list)

plus_list = set_X | set_Y
multi_list = set_X & set_Y
sub_list = set_X - set_Y

print("X_list=",X_list)
print("Y_list=",Y_list)
print("set_X=",set_X)
print("set_Y=",set_Y)
print("plus_list=",plus_list)
print("multi_list=",multi_list)
print("sub_list=",sub_list)
print("seをset_Xに含んでいる場合はtrue",set_X.issuperset(set_msg3))
print("seをset_Yに含んでいる場合はtrue",set_Y.issuperset(set_msg3))

素人の言語処理100本ノック:06
https://qiita.com/segavvy/items/209bf27d4cee51f60f99

# coding: utf-8


def n_gram(target, n):
    '''指定されたリストからn-gramを作成

    引数:
    target -- 対象リスト
    n -- n-gramのn値(1ならuni-gram、2ならbi-gram...)
    戻り値:
    gramのリスト
    '''
    result = []
    for i in range(0, len(target) - n + 1):
        result.append(target[i:i + n])

    return result



# 集合の作成
set_x = set(n_gram('paraparaparadise', 2))
print('X:' + str(set_x))
set_y = set(n_gram('paragraph', 2))
print('Y:' + str(set_y))

# 和集合
set_or = set_x | set_y
print('和集合:' + str(set_or))

# 積集合
set_and = set_x & set_y
print('積集合:' + str(set_and))

# 差集合
set_sub = set_x - set_y
print('差集合:' + str(set_sub))

# 'se'が含まれるか?
print('seがXに含まれる:' + str('se' in set_x))
print('seがYに含まれる:' + str('se' in set_y))

言語処理100本ノック 06~09
https://qiita.com/gita/items/5b435f530e4aa4736092

#!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)

Python100本ノック(10/100)
https://qiita.com/ikura1/items/b63e26f5b390e8bda625

a = 'paraparaparadise'
b = 'paragraph'
n = 2
x = set(n_gram(a, 2))
y = set(n_gram(b, 2))
print(x | y)  # wa
print(x & y)  # seki
print(x - y)  # sa
print('se' in x)
print('se' in y)

言語処理100本ノック ~1章まで
https://qiita.com/esaka/items/58a7ff850486fb6ca2c4

import re # 正規表現の利用

# シーケンスとして文字列とリスト用意
X = "paraparaparadise"
Y = "paragraph"

# n-gram関数 05の再利用
def n_gram(n,sequence):

    ngram = []

    if isinstance(sequence, str):
        sequence = list(re.sub('[,. ]','',sequence))

    for i in range(len(sequence)-n+1):
        # 05と変えた箇所、リスト内リストだと後述のset型に変換できなかったので
        # タプル型に変換処理を入れている
        ngram.append(tuple(sequence[i:i+n]))

    return ngram

# X,Y のbi-gram作成
# 集合計算のためにset型で定義
X = set(n_gram(2,X))
Y = set(n_gram(2,Y))

#  和集合
print(X | Y)
#  積集合
print(X & Y)
#   差集合
print(X - Y)
print(Y - X)
#  'se'が含まれるかチェック
if ('s','e') in X & Y:
    print("'se'はX及びYに含まれます")
else:
    print("'se'はXもしくはYに含まれていません")

言語処理100本ノック 00〜09
https://qiita.com/nubilum/items/af0a2ff057b9a6d708ad

def ngram(target, n):
    ngram = []
    for i in range(len(target) - n + 1):
        ngram.append(target[i:(i + n)])
    return ngram

X = set(ngram("paraparaparadise", 2))
Y = set(ngram("paragraph", 2))

print(X | Y)
print(X & Y)
print(X - Y)

言語処理100本ノックを解いてみよう! 1章
https://qiita.com/Ikeda_yu/items/85371ae96f6ab6708cc9

def p7():
    X = p6("paraparaparadise", 2)[0]
    Y = p6("paragraph", 2)[0]

    # 集合型に変換する
    X, Y = set(X), set(Y)

    return "和集合は" + str(X | Y), "積集合は" + str(X & Y), "差集合は" + str(X ^ Y), "Xは" + str("se" in X) + "です", "Yは" + str("se" in Y) + "です"

if __name__ == "__main__":
    print(p7())

言語処理100本ノックから
https://qiita.com/melito/items/d0fab8c7e958e4a6cbb0

  def sortAndDedupe[A <% Ordered[A]](seq: Seq[A]): Seq[A] = {
    def msort[A](comp: (A, A) => Boolean)(xs: Seq[A]): Seq[A] = {
      def merge(xs1: Seq[A], xs2: Seq[A]): Seq[A] = {
        if (xs1.isEmpty) {
          xs2
        } else if (xs2.isEmpty) {
          xs1
        } else if (comp(xs1.head, xs2.head)) {
          xs1.head +: merge(xs1.tail, xs2)
        } else {
          xs2.head +: merge(xs1, xs2.tail)
        }
      }
      val n = xs.length / 2
      if (n == 0) xs
      else merge(msort(comp)(xs take n), msort(comp)(xs drop n))
    }

    val s = msort((x: A, y: A) => x < y)(seq.toList)
    s.distinct
  }
def msort[A](comp: (A, A) => Boolean)(list: List[A]): List[A] = {
  def merge(first: List[A], second: List[A]): List[A] = {
    (first, second) match {
      case (x :: xs, ys@(y :: _)) if comp(x, y) => x :: merge(xs, ys)
      case (xs, y :: ys)                        => y :: merge(xs, ys)
      case (xs, Nil)                            => xs
      case (Nil, ys)                            => ys
    }
  }
  val n = list.length / 2
  if (n == 0) list
  else merge(msort(comp)(list take n), msort(comp)(list drop n))
}

def distinct[A](list: List[A]): List[A] = {
  def exists[A](p: A => Boolean)(l: List[A]): Boolean = l match {
    case head :: tail => p(head) || exists(p)(tail)
    case _ => false
  }
  var result = List[A]()
  for (elem <- list) {
    if(!exists((x: A) => x == elem)(result)) result = elem :: result
  }
  result.reverse
}

val list = List(1,2,3,4,2,3,4,99)
val s = msort((x: Int, y: Int) => x < y)(list)

println(list)           // List(1, 2, 3, 4, 2, 3, 4, 99)
println(s)              // List(1, 2, 2, 3, 3, 4, 4, 99)
println(distinct(s))    // List(1, 2, 3, 4, 99)

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

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

言語処理100本ノック : 第1章
https://qiita.com/Scstechr/items/debb5d67eba811df812c

def gen_sentence(x, y, z):
    return f'{x}時の{y}{z}'

print(gen_sentence(12, '気温', 22.4))

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

temp = lambda x, y, z: "{0}時の{1}は{2}".format(x, y, z)

print(temp(12, "気温", 22.4))

言語処理100本ノック 第1章 準備運動
https://qiita.com/dwarfer7634/items/1cdc22a4ee6b74ec761a

def to_sentence(X, Y, Z):
    return '{0}時の{1}は{2}'.format(X, Y, Z)

to_sentence(12, '気温', 22.4)

言語処理100本ノック 第1章
https://qiita.com/nozma/items/4fb81dde4e33ad5ec3f7

# coding: utf-8

def gen_sentence(x, y, z):
    return "{}時の{}は{}".format(x, y, z)

x = 12
y = '気温'
z = 22.4
print(gen_sentence(x, y, z))

【python】100本ノックにチャレンジ!(006〜009)
https://qiita.com/masassy/items/4bd0b901e2fa5b43dd48

from string import Template

def template_print(x,y,z):
    value ={'time':x,'name':y,'tempture':z}
    t = Template("$time時の$nameは$tempture")
    return print(t.substitute(value))

if __name__ == "__main__":
    x=12
    y='気温'
    z=22.4
    template_print(x,y,z)

言語処理100本ノックを解いてみよう! 1章
https://qiita.com/Ikeda_yu/items/85371ae96f6ab6708cc9

def p8(x, y, z):
    return "{}時の{}は{}".format(x, y, z)

if __name__ == "__main__":
  print(p8(12, "気温", 22.4))

08. 暗号文

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

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

言語処理100本ノック : 第1章
https://qiita.com/Scstechr/items/debb5d67eba811df812c

p08.py
def cipher(string):
    return ''.join(chr(219-ord(c)) if c.islower() else c for c in string)

string = "I couldn't believe that I could actually understand what I was reading"
print(string)
print(cipher(string))         # encoded
print(cipher(cipher(string))) # decoded

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

cipher = lambda string: "".join(chr(219 - ord(c)) if c.islower() else c for c in string)

string = cipher("It is 8:30 in San Francisco now.")
print(string)
string = cipher(string)
print(string)

言語処理100本ノック 第1章 準備運動
https://qiita.com/dwarfer7634/items/1cdc22a4ee6b74ec761a

def cipher(sentence):
    rets = ''
    for c in sentence:
        if c.islower():
            rets += chr(219 - ord(c))
        else :
            rets += c
    return rets

row_data = 'We are going to use A strategy tomorrow.'
print('row data : ', row_data)
encrypted_data = cipher(row_data)
print('encrypted data : ', encrypted_data)
decrypted_data = cipher(encrypted_data)
print('decrypted data : ', decrypted_data)

言語処理100本ノック 第1章
https://qiita.com/nozma/items/4fb81dde4e33ad5ec3f7

【python】100本ノックにチャレンジ!(006〜009)
https://qiita.com/masassy/items/4bd0b901e2fa5b43dd48

cipher_008.py
import re

def cipher(msg):
    pattern = re.compile("[a-z]")
    cipher_msg = ''
    for temp in msg:
        if pattern.match(temp):
            cipher_msg += chr(219-ord(temp))
            continue
        else:
            cipher_msg += temp
            continue
    return  cipher_msg

if __name__=="__main__":
    msg = "Cipher_msg_012345"
    print("元msg=",msg)
    c = cipher(msg)
    print("暗号化=",c)
    d = cipher(c)
    print("復号化=",d)

09. Typoglycemia

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

言語処理100本ノック : 第1章
https://qiita.com/Scstechr/items/debb5d67eba811df812c

p09-EX.py
import random

string = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
str_lst = string.split(' ')

idx_lst = [idx for idx, word in enumerate(str_lst) if len(word) > 4]
random.shuffle(idx_lst)

[idx_lst.insert(idx, idx) for idx in range(len(str_lst)) if idx not in idx_lst]

string = ' '.join(str_lst[i] for i in idx_lst)

言語処理100本ノック 第1章
https://qiita.com/kokorinosoba/items/ac46fb47ab236b15687b

def typoglycemia(sentence):
    words = sentence.split()
    typo = []
    for word in words:
        if len(word) > 3:
            listed_word = list(word[1:-1])
            middle = np.random.permutation(listed_word)
            middle = "".join(middle)
            typo.append(word[0] + middle + word[-1])
        else:
            typo.append(word)
    typo = " ".join(typo)
    return typo

言語処理100本ノック 第1章 準備運動
https://qiita.com/dwarfer7634/items/1cdc22a4ee6b74ec761a

import numpy as np

def random_swap(sentence):
    words = sentence.split()
    rets = ''
    for word in words:
        if len(word) > 4:
            rets += word[0]
            for i in np.random.permutation(range(1,len(word) - 1)) :
                rets += word[i]
            rets += word[-1] + ' '
        else :
            rets += word + ' '

    return rets.rstrip(' ')

sentence = 'I couldn\'t believe that I could actually understand what I was reading : the phenomenal power of the human mind .'
print('original : ', sentence)
print('swapped : ', random_swap(sentence))

言語処理100本ノック 第1章
https://qiita.com/nozma/items/4fb81dde4e33ad5ec3f7

# coding: utf-8

import numpy.random as rd

def gen_typo(S):
    if len(S) <= 4:
        return S
    else:
        idx = [0]
        idx.extend(rd.choice(range(1, len(S)-1), len(S)-2, replace=False))
        idx.append(len(S)-1)
        result = []
        for i in range(len(S)):
            result.append(S[idx[i]])
        return ''.join(result)

s = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
s = s.split()
print(' '.join([gen_typo(i) for i in s]))

考察

数(長さ)

行数、1行の文字数、全体の文字数

実行時間

データを100倍くらいにして測定するとよいかも。

多岐度

変数、関数、条件分岐の多岐度が同じでも可読性は違う可能性がある。

変数数(多岐度)

 幾つの変数を使ったか

関数数(多岐度)

 幾つの関数を使ったか。

条件分岐数(多岐度)

 何階層の深さと、幾つの広さの条件分岐を行ったか。

<この記事は個人の過去の経験に基づく個人の感想です。現在所属する組織、業務とは関係がありません。>

文書履歴

ver. 0.10 初稿 00 記載 20180411
ver. 0.11 01, 02 追記 20180411
ver. 0.12 03, 04 追記 20180412
ver. 0.13 動作確認docker環境構築 追記 20180412
ver. 0.14 考察 追記 20180413
ver. 0.15 06,07 追記 20180813
ver. 0.16 5項目洗い出し追記 20181105
ver. 0.17 08, 09 追記 20190123
ver. 0.18 リストの逆順 追記 20190131
ver. 0.19 誤植訂正 20190427
ver. 0.20 docker 追記 20210724
ver. 0.21 ありがとう追記 20230521

最後までおよみいただきありがとうございました。

いいね 💚、フォローをお願いします。

Thank you very much for reading to the last sentence.

Please press the like icon 💚 and follow me for your happy life.

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
14