タイトルケース (Title Case) を理解する
このステップでは、タイトルや見出しで一般的に使用される大文字小文字のスタイルであるタイトルケースについて学びます。タイトルケースを理解することは、テキストを正しくフォーマットし、読みやすさを確保するために不可欠です。
タイトルケースとは、冠詞 (a, an, the)、前置詞 (of, in, to)、接続詞 (and, but, or) などの特定の小さな単語を除き、各単語の最初の文字が大文字になるスタイルを指します。ただし、タイトルの最初と最後の単語は、その種類に関係なく常に大文字になります。
では、タイトルケースを調べるための Python スクリプトを作成して始めましょう。
-
LabEx 環境で VS Code エディタを開きます。
-
~/project
ディレクトリに title_case.py
という名前の新しいファイルを作成します。
touch ~/project/title_case.py
-
エディタで title_case.py
ファイルを開きます。
-
以下の Python コードをファイルに追加します。
def to_title_case(text):
minor_words = ['a', 'an', 'the', 'of', 'in', 'to', 'and', 'but', 'or']
words = text.split()
title_cased_words = []
for i, word in enumerate(words):
if i == 0 or i == len(words) - 1 or word not in minor_words:
title_cased_words.append(word.capitalize())
else:
title_cased_words.append(word.lower())
return ' '.join(title_cased_words)
text1 = "the quick brown fox"
text2 = "learning python is fun"
print(to_title_case(text1))
print(to_title_case(text2))
このコードは、与えられた文字列をタイトルケースに変換する to_title_case
関数を定義しています。文字列は単語に分割され、各単語の最初の文字が大文字になり(小さな単語を除く)、その後単語が再度結合されます。
-
title_case.py
ファイルを保存します。
-
ターミナルで python
コマンドを使用してスクリプトを実行します。
python ~/project/title_case.py
以下の出力が表示されるはずです。
The Quick Brown Fox
Learning Python Is Fun
この出力は、スクリプトが入力文字列の各重要な単語の最初の文字を大文字にしてタイトルケースに変換する様子を示しています。