在 MATLAB 中反向讀取檔案中的單詞
假設一個文字檔案包含一個句子“I Study MATLAB from Tutorials Point.”。現在,我們想要以相反的順序讀取文字檔案中的這些單詞,結果將是“Point Tutorials from MATLAB Study I.”。在本文中,我們將探討實現 MATLAB 程式以反向讀取文字檔案中的單詞。
演算法:反向讀取檔案中的單詞
在 MATLAB 中,我們必須按照以下步驟反向讀取檔案中的單詞
步驟 1 - 透過呼叫函式“fopen()”開啟檔案以進行讀取。此函式採用兩個引數,即檔案路徑和訪問模式。對於“讀取模式”,“r”用作訪問模式。此函式返回一個檔案識別符號“FileID”,用於引用已開啟的檔案。
步驟 2 - 檢查給定檔案是否已成功開啟。為此,將“fileID”的值與“-1”進行比較。如果“FileID”等於“-1”,則將顯示一個錯誤,指出無法開啟檔案。
步驟 3 - 使用函式“fscan()”讀取檔案的內容。此函式採用兩個引數,即檔案識別符號 (“FileID”) 和格式說明符 (“%c”)。這裡,格式說明符“%c”用於從檔案中讀取字元。然後,開啟的檔案內容儲存在變數“content”中。
步驟 4 - 使用函式“fclose()”關閉檔案以釋放系統資源。此函式採用檔案識別符號,即“FileID”作為引數。
步驟 5 - 使用函式“strsplit()”將檔案內容拆分為單詞。
步驟 6 - 使用函式“flip()”反轉單詞的順序。
步驟 7 - 使用函式“disp()”顯示反轉後的單詞。
現在讓我們考慮一個 MATLAB 程式示例,以瞭解如何反向讀取檔案中的單詞。
示例
% MATLAB program to demonstrate read words in a file in reverse order
% Create a text file
str = 'I Study from Tutorials Point';
FileID = fopen('tutorials_point.txt','w');
fprintf(FileID,'%s',str);
fclose(FileID);
% Open the file for reading its content
FileID = fopen('tutorials_point.txt', 'r');
% Check for successful file opening
if FileID == -1
error('Failed to open the file.');
end
% Read the file content
content = fscanf(FileID, '%c');
% Close the file to free up resources
fclose(FileID);
% Split the file content into words
words = strsplit(content);
% Reverse the order of words
reversed_words = flip(words);
% Display the reversed words
disp('Words in the Reverse Order:')
disp(reversed_words)
輸出
Words in the Reverse Order:
{
[1,1] = Point
[1,2] = Tutorials
[1,3] = from
[1,4] = Study
[1,5] = I
}
解釋
在上面的 MATLAB 程式中,我們首先使用訪問模式“w”呼叫函式“fopen”來建立一個文字檔案。然後,我們使用“r”呼叫函式“fopen”以開啟檔案以讀取其內容。之後,我們檢查檔案是否已成功開啟。如果檔案未開啟,則會顯示錯誤。
我們使用“%c”作為格式說明符呼叫函式“fscanf”以讀取其內容。然後,我們呼叫函式“fclose”關閉檔案以釋放系統資源。現在,我們呼叫函式“strsplit”將內容拆分為單詞,並將這些單詞儲存在變數“words”中。之後,我們呼叫函式“flip”反轉單詞的順序。最後,我們呼叫函式“disp”顯示反轉後的單詞。
結論
要執行此操作,MATLAB 有一個函式“flip()”,它反轉輸入給它的單詞的順序。上面 MATLAB 中的示例程式演示了檔案中單詞順序的反轉。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP