トラック
/
Python
Python
/
演習
/
妹の語彙
妹の語彙

妹の語彙

学習演習

はじめに

Pythonのstrは、Unicodeコードポイントのイミュータブルなシーケンスです。 これには、文字、発音区別符号、位置指定文字、数字、通貨記号、絵文字、句読点、空白文字、改行文字などが含まれます。 イミュータブルなので、メモリ上にあるstrオブジェクトの値は変わりません。文字列を変更するように見えるメソッドは、そのstrオブジェクトの新しいコピー(またはインスタンス)を返します。

strリテラルは、一重引用符'または二重引用符"で宣言できます。エスケープ文字\は、必要に応じて使えます。


>>> single_quoted = 'These allow "double quoting" without "escape" characters.'

>>> double_quoted = "These allow embedded 'single quoting', so you don't have to use an 'escape' character."

>>> escapes = 'If needed, a \'slash\' can be used as an escape character within a string when switching quote styles won\'t work.'

複数行の文字列は、'''または"""で宣言します。

>>> triple_quoted =  '''Three single quotes or "double quotes" in a row allow for multi-line string literals.
  Line break characters, tabs and other whitespace are fully supported.

  You\'ll most often encounter these as "doc strings" or "doc tests" written just below the first line of a function or class definition.
    They\'re often used with auto documentation ✍ tools.
    '''

文字列は+演算子で連結できます。 この方法は、性能が良くなく保守も簡単ではないため、使うのは控えめにしましょう。

language = "Ukrainian"
number = "nine"
word = "дев'ять"

sentence = word + " " + "means" + " " + number + " in " + language + "."

>>> print(sentence)
...
"дев'ять means nine in Ukrainian."

複数のlist、tuple、setなどのコレクションを1つのstrにまとめる必要がある場合は、<str>.join(<iterable>)のほうが適しています。

# str.join() makes a new string from the iterables elements.
>>> chickens = ["hen", "egg", "rooster"] # Lists are iterable.
>>> ' '.join(chickens)
'hen egg rooster'

# Any string can be used as the joining element.
>>> ' :: '.join(chickens)
'hen :: egg :: rooster'

>>> ' 🌿 '.join(chickens)
'hen 🌿 egg 🌿 rooster'


# Any iterable can be used as input.
>>> flowers = ("rose", "daisy", "carnation")  # Tuples are iterable.
>>> '*-*'.join(flowers)
'rose*-*daisy*-*carnation'

>>> flowers = {"rose", "daisy", "carnation"}  # Sets are iterable, but output order is not guaranteed.
>>> '*-*'.join(flowers)
'rose*-*carnation*-*daisy'

>>> phrase = "This is my string"  # Strings are iterable, but be careful!
>>> '..'.join(phrase)
'T..h..i..s.. ..i..s.. ..m..y.. ..s..t..r..i..n..g'


# Separators are inserted **between** elements, but can be any string (including spaces).
# This can be exploited for interesting effects.
>>> under_words = ['under', 'current', 'sea', 'pin', 'dog', 'lay']
>>> separator = ' ⤴️ under'
>>> separator.join(under_words)
'under ⤴️ undercurrent ⤴️ undersea ⤴️ underpin ⤴️ underdog ⤴️ underlay'

# The separator can be composed different ways, as long as the result is a string.
>>> upper_words = ['upper', 'crust', 'case', 'classmen', 'most', 'cut']
>>> separator = ' 🌟 ' + upper_words[0]
>>> separator.join(upper_words)
 'upper 🌟 uppercrust 🌟 uppercase 🌟 upperclassmen 🌟 uppermost 🌟 uppercut'

str内のコードポイントは、左から0-based indexの番号で参照できます。

creative = '창의적인'

>>> creative[0]
'창'

>>> creative[2]
'적'

>>> creative[3]
'인'

インデックスは右からも行えます。その場合は-1-based indexから始まります。

creative = '창의적인'

>>> creative[-4]
'창'

>>> creative[-2]
'적'

>>> creative[-1]
'인'

Pythonには、独立した「文字」型や「ルーン」型はありません。そのため、文字列にインデックスを付けると、長さ1の新しいstrが生成されます。


>>> website = "exercism"
>>> type(website[0])
<class 'str'>

>>> len(website[0])
1

>>> website[0] == website[0:1] == 'e'
True

_スライス記法_を使うと、部分文字列を選択できます。<str>[<start>:stop:<step>]を使うと、新しい文字列が生成されます。 結果にはstopのインデックスの文字は含まれません。 startを指定しない場合、開始インデックスは0になります。 stopを指定しない場合、終了インデックスは文字列の末尾になります。

moon_and_stars = '🌟🌟🌙🌟🌟⭐'
sun_and_moon = '🌞🌙🌞🌙🌞🌙🌞🌙🌞'

>>> moon_and_stars[1:4]
'🌟🌙🌟'

>>> moon_and_stars[:3]
'🌟🌟🌙'

>>> moon_and_stars[3:]
'🌟🌟⭐'

>>> moon_and_stars[:-1]
'🌟🌟🌙🌟🌟'

>>> moon_and_stars[:-3]
'🌟🌟🌙'

>>> sun_and_moon[::2]
'🌞🌞🌞🌞🌞'

>>> sun_and_moon[:-2:2]
'🌞🌞🌞🌞'

>>> sun_and_moon[1:-1:2]
'🌙🌙🌙🌙'

<str>.split(<separator>)を使うと、文字列をより小さな文字列に分割できます。これは部分文字列のlistを返します。 必要に応じて、そのリストにさらにインデックスを付けたり分割したりできます。 <str>.split()を引数なしで使うと、空白文字で文字列を分割します。

>>> cat_ipsum = "Destroy house in 5 seconds mock the hooman."
>>> cat_ipsum.split()
...
['Destroy', 'house', 'in', '5', 'seconds', 'mock', 'the', 'hooman.']


>>> cat_ipsum.split()[-1]
'hooman.'


>>> cat_words = "feline, four-footed, ferocious, furry"
>>> cat_words.split(', ')
...
['feline', 'four-footed', 'ferocious', 'furry']

<str>.split()の区切り文字は、複数の文字でもかまいません。 分割の照合には文字列全体が使われます。


>>> colors = """red,
orange,
green,
purple,
yellow"""

>>> colors.split(',\n')
['red', 'orange', 'green', 'purple', 'yellow']

文字列は、すべての共通シーケンス操作をサポートしています。 個々のコードポイントは、for item in <str>でループして繰り返し処理できます。 インデックス_と_要素の組は、for index, item in enumerate(<str>)でループして繰り返し処理できます。


>>> exercise = 'လေ့ကျင့်'

# Note that there are more code points than perceived glyphs or characters
>>> for code_point in exercise:
...    print(code_point)
...
လ
ေ
့
က
ျ
င
်
့

# Using enumerate will give both the value and index position of each element.
>>> for index, code_point in enumerate(exercise):
...    print(index, ": ", code_point)
...
0 :  လ
1 :  ေ
2 :  ့
3 :  က
4 :  ျ
5 :  င
6 :  ်
7 :  ့

説明

妹の英語の語彙の宿題を手伝っています。妹はその宿題をとても退屈に感じています。妹のクラスでは、_接頭辞_と_接尾辞_を付けて新しい単語を作ることを学んでいます。先生は、与えられた単語のセットに対して、単語の先頭に接頭辞を、あるいは末尾に接尾辞を付けて、正しくつづられた変換後の単語を求めています。

この課題には4つのアクティビティがあり、それぞれに取り組むテキストや単語のセットがあります。

1. 単語に接頭辞を付ける

英語で最もよく使われる接頭辞の1つがunで、「~でない」という意味です。このアクティビティでは、妹は単語にunを付けて、否定の、つまり「~でない」という意味の単語を作る必要があります。

wordを入力として受け取り、unが付いた新しい単語を返すadd_prefix_un(<word>)関数を実装してください。

>>> add_prefix_un("happy")
'unhappy'

>>> add_prefix_un("manageable")
'unmanageable'

2. 単語のグループに接頭辞を付ける

妹のクラスでは、さらに4つのよく使われる接頭辞を学んでいます。 en(『中に入れる』あるいは『~で覆う』という意味)、 pre(『前に』あるいは『前方へ』という意味)、 auto(『自分自身』あるいは『同じ』という意味)、 そしてinter(『~の間』あるいは『~の中で』という意味)です。

この演習では、クラスはこれらの接頭辞を使って語彙のグループを作り、まとめて学習できるようにします。それぞれの接頭辞は、よく一緒に使われる単語のリストとして与えられます。生徒は接頭辞を適用し、すべての単語に接頭辞を付けた結果を表す文字列を作る必要があります。

次の形式のvocab_wordsを入力として受け取り、それぞれの単語に接頭辞を付けた文字列を返すmake_word_groups(<vocab_words>)関数を実装してください。 [<prefix>, <word_1>, <word_2> .... <word_n>]という形式で、返す文字列は'<prefix> :: <prefix><word_1> :: <prefix><word_2> :: <prefix><word_n>'のような形になります。

ここでは、入力を処理するためにforループやwhileループを書く必要はありません。代わりにどの文字列メソッド(と区切り文字)を使えるか、よく考えてみましょう。

>>> make_word_groups(['en', 'close', 'joy', 'lighten'])
'en :: enclose :: enjoy :: enlighten'

>>> make_word_groups(['pre', 'serve', 'dispose', 'position'])
'pre :: preserve :: predispose :: preposition'

>> make_word_groups(['auto', 'didactic', 'graph', 'mate'])
'auto :: autodidactic :: autograph :: automate'

>>> make_word_groups(['inter', 'twine', 'connected', 'dependent'])
'inter :: intertwine :: interconnected :: interdependent'

3. 単語から接尾辞を取り除く

nessはよく使われる接尾辞で、_『~である状態』_という意味です。 このアクティビティでは、妹はnessという接尾辞を取り除いて、元の語根を見つける必要があります。 ただし、厄介なつづりのルールがあります。元の語根が子音のあとに'y'が続く形で終わっていた場合、その'y'は'i'に変わっています。'ness'を取り除くときは、そうした語根の'y'を元に戻す必要があります。たとえばhappiness --> happi --> happyです。

wordを受け取り、nessという接尾辞を取り除いた語根を返すremove_suffix_ness(<word>)関数を実装してください。

>>> remove_suffix_ness("heaviness")
'heavy'

>>> remove_suffix_ness("sadness")
'sad'

4. 単語を取り出して変換する

接尾辞は、単語の品詞を変えるためによく使われます。 英語では、よく「verbing」や「verbifying」が行われます。これは、形容詞がenという接尾辞を付けることで_動詞になる_というものです。

このタスクでは、妹は文から形容詞を取り出して動詞に変えるという「verbing」を練習します。 幸いなことに、ここで変換する必要がある単語はすべて「規則的」で、接尾辞を付けるのにつづりを変える必要はありません。

2つの入力を受け取るadjective_to_verb(<sentence>, <index>)関数を実装してください。 1つは語彙の単語を使ったsentence、もう1つはその文を分割したときの単語のindexです。 関数は、取り出した形容詞を動詞にして返します。

>>> adjective_to_verb('I need to make that bright.', -1 )
'brighten'

>>> adjective_to_verb('It got dark as the sun set.', 2)
'darken'
GitHubで編集する リンクは新しいウィンドウまたはタブで開きます
Python Exercism

妹の語彙を始める準備はできましたか?

Exercismに登録すれば、17個のコンセプト146個の演習、そして本物の人間によるメンタリングとともに、Pythonを学んでマスターできます。すべて無料です。