building_block.oxford_comma

文字列のリストから並列文を作成する関数

概要

文字列のリストを与えると、リストの要素を英文における並列文の形に変換する関数です。表記法については Wikipedia Serial comma を参照し、コードについては stack overflow:Grammatical List Join in Python [duplicate] を参照しました。

oxford_comma(
    x: Union[str, List[str]], 
    sep_last: str = "and", 
    quotation: bool = True
    )

oxford_comma_and(
    x: Union[str, List[str]], 
    quotation: bool = True
    )

oxford_comma_or(
    x: Union[str, List[str]], 
    quotation: bool = True
    )

oxford_comma_shorten(
    x: Union[str, List[str]],
    sep_last: str = 'and', 
    quotation: bool = True, 
    suffix: str = 'items', 
    max_items: Optional[int] = None,
    max_width: int = 80,
    abbreviate: bool = True
)

引数

  • xstr or list of str
  • sep_last: str oxford_comma() のみ
     リストの最後の要素の直前に付加する単語を表す文字列。
  • quotation: bool
     リストの各要素にクオーテーションマーク ’’ を追加するかどうかを表す論理値。True(初期設定)であればクオーテーションマークを追加し、False であれば追加しません。
  • suffixstr oxford_comma_shorten() のみ
    省略された要素を表すための補足語。"other N items"items の部分に使用されます。
  • max_itemsint oxford_comma_shorten() のみ
    abbreviate=True の時に表示する要素の最大個数。max_items が指定され、かつ x 数より少ない場合、出力には最初の max_items 個のアイテムが表示され、その後 "and other N {suffix}" の表記が追加されます。None の場合、テキスト幅に基づいて省略処理が行われます。
  • max_widthint oxford_comma_shorten() のみ
    出力される文字列の最大幅。返り値の文字列がこの幅を超える場合、省略処理が行われます。デフォルトは80です。
  • abbreviate: bool oxford_comma_shorten() のみ
    省略処理を許可するかどうか。False を指定した場合、x の要素数や文字幅に関わらず常に全文を返します。デフォルトは True です。abbreviate = False が指定された場合、oxford_comma_shorten() の動作は oxford_comma() と同等になります。

なお、oxford_comma_and(x)oxford_comma(x, 'and') と、oxford_comma_or(x)oxford_comma(x, 'or') と同等です。oxford_comma_shorten() は、生成されたテキストが指定された文字幅を超える場合に、自動的に省略表示を行います。省略が発生した場合は、"and other N items" のように、省略された要素の数が分かる表現を付加します。

使用例 Example

from py4stats import building_block as build
x = ['A', 'B', 'C']

print(build.oxford_comma_and(x))
#> 'A', 'B' and 'C'

print(build.oxford_comma_and(x, quotation = False))
#> A, B and C

print(build.oxford_comma_or(x))
#> 'A', 'B' or 'C'

リストの要素が1つの場合、あるいは x に文字列が指定された場合はカンマなどを追加せずにそのまま出力します。

print(build.oxford_comma_or(['A']))
#> 'A'

print(build.oxford_comma_or('A'))
#> 'A'

リストの要素が1つの場合、あるいは x に文字列が指定された場合はカンマなどを追加せずにそのまま出力します。

import string
alpha = list(string.ascii_lowercase)
        
print(build.oxford_comma_shorten(alpha))
#> "'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' and other 14 items"
        
print(build.oxford_comma_shorten(alpha, max_width = 40))
#> "'a', 'b', 'c', 'd' and other 22 items"

# リストが十分に短い場合は、省略されません
print(build.oxford_comma_shorten(alpha[:10]))
#> "'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' and 'j'"

Return to Function reference.