Main Content

MATLAB에서 Python 함수를 호출하여 단락 텍스트 줄 바꾸기

이 예제에서는 MATLAB® 내에서 Python® 언어의 함수와 모듈을 사용하는 방법을 보여줍니다. 이 예제는 Python 표준 라이브러리에서 텍스트 서식 지정 모듈을 호출합니다.

MATLAB은 종종 CPython이라고 부르는 Python의 참조 구현을 지원합니다. Mac이나 Linux 플랫폼을 사용 중이면 이미 Python이 설치되어 있습니다. Windows를 사용 중인 경우 https://www.python.org/downloads/에서 Python 배포판을 다운로드하여 설치할 수 있습니다. 자세한 내용은 지원되는 Python 구현 설치하기 항목을 참조하십시오.

Python textwrap 모듈 사용하기

MATLAB은 Python 표준 라이브러리 기능과 동등한 기능을 많이 갖추고 있지만 모든 기능을 갖추고 있지는 않습니다. 예를 들어, textwrap은 캐리지 리턴과 그 밖의 다른 편의 함수를 사용하여 텍스트 블록의 형식을 지정하는 모듈입니다. MATLAB도 textwrap 함수를 제공하지만 MATLAB의 이 함수는 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 문자열로 변환하기

함수 이름 앞에 문자 py.를 입력하여 textwrap.wrap 함수를 호출합니다. 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 사용자가 사용할 수 있는 또 다른 라이브러리 소스라는 점만 알고 있으면 충분합니다. 튜플(Tuple), 사전(Dictionary) 등의 Python 데이터형을 포함하여 MATLAB과 Python 간에 데이터를 이동하는 방법에 대한 자세한 내용은 MATLAB에서 Python 호출하기 항목을 참조하십시오.