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 字符串

通过在 textwrap.wrap 函数名称之前输入字符 py. 来调用该函数。请勿输入 import textwrap

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

  W         1x3                 8  py.list              

W 是一个 Python 列表,MATLAB 将其显示为 py.list 类型。每个元素均为一个 Python 字符串。

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

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

py.list 转换为字符串数组。

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_indentsubsequent_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 用户所需的库就足够了。如果您想了解 MATLAB 和 Python 之间的数据移动情况,包括元组和字典等 Python 数据类型,请参阅从 MATLAB 中调用 Python