Main Content

MATLAB での Python 関数の呼び出しによる段落テキストの折り返し

この例では、MATLAB® 内で Python® 言語の関数およびモジュールを使用する方法を説明します。例では、Python 標準ライブラリからテキストの書式設定モジュールを呼び出します。

MATLAB は、Python の参照実装 (通称 CPython) をサポートします。Mac または Linux プラットフォームを使用している場合、Python は既にインストールされています。Windows を使用している場合、https://www.python.org/downloads/ などにある配布版をインストールする必要があります。詳細については、サポートされている Python 実装のインストールを参照してください。

Python textwrap モジュールの使用

MATLAB にも Python 標準ライブラリの多くの機能に相当する機能がありますが、すべてが備わっているわけではありません。たとえば、テキストのブロックをキャリッジ リターンや他の簡易関数により書式設定する textwrap というモジュールがあります。MATLAB も関数 textwrap を提供していますが、これは、UI コントロールの中に収まるようテキストを折り返します。

使用するテキストの段落を作成します。

T = "We at MathWorks believe in the importance of engineers and scientists. They increase human knowledge and profoundly improve our standard of living.";

Python 文字列の MATLAB string への変換

関数 textwrap.wrap を呼び出すには、関数名の前に py. という文字を入力します。import textwrap と入力しないでください。

W = py.textwrap.wrap(T);
whos W
  Name      Size            Bytes  Class      Attributes

  W         1x3                 8  py.list              

W は、MATLAB で py.list 型として表示される Python リストです。各要素は Python 文字列です。

W{1}
ans = 
  Python str with no properties.

    We at MathWorks believe in the importance of engineers and scientists.

py.list を string 配列に変換します。

wrapped = string(W);
whos wrapped
  Name         Size            Bytes  Class     Attributes

  wrapped      1x3               514  string              
wrapped(1)
ans = 
"We at MathWorks believe in the importance of engineers and scientists."

段落のカスタマイズ

キーワード引数を使用して、段落の出力をカスタマイズします。

前のコードでは簡易関数 wrap を使用しましたが、このモジュールでは py.textwrap.TextWrapper 機能を使用してさらに多くのオプションが提供されています。オプションを使用するには、https://docs.python.org/2/library/textwrap.html#textwrap.TextWrapper で説明されているキーワード引数を指定して、py.textwrap.TextWrapper を呼び出します。

width キーワードを使用して、テキストを 30 文字の幅に書式設定します。initial_indent および subsequent_indent のキーワードにより、各行の先頭に MATLAB で使用されるコメント文字 % が表示されます。

tw = py.textwrap.TextWrapper(initial_indent="% ",subsequent_indent="% ",width=int32(30));
W = wrap(tw,T);

MATLAB 引数に変換し、結果を表示します。

message = string(W);
fprintf("%s\n", message{:})
% We at MathWorks believe in
% the importance of engineers
% and scientists. They
% increase human knowledge and
% profoundly improve our
% standard of living.

詳細

ここでは、Python が MATLAB ユーザーにとって利用可能なもう 1 つのライブラリのソースであるということを記憶に留めれば十分です。タプルや辞書などの Python データ型を含めた、MATLAB と Python 間でのデータのやり取りについては、MATLAB からの Python の呼び出しを参照してください。