忽略特殊字符,同时使用 MATLAB 的 fprintf 函数保留格式



我在一个名为"dataString"的matlab脚本中有一个字符串数组,它是使用fileread()从html文档复制到matlab中的。然后,我剪切出我想要的部分,并将其存储在dataString中。

TEXT = fileread(htmldocument);
k1 = strfind(TEXT,stringDelimiter1)
k2 = strfind(TEXT,stringDelimiter2)
dataString(:) = TEXT(k1(1):(k1(1) - 1))

然后对其内容进行了过滤,使其不包含html代码,但除了字母外,它仍然可以包含特殊字符和数字。下面dataString内容的解决方案应该足以满足我试图解决的问题的一般情况。dataString中有各种字符和数字,并且在文本中有特定的点,在MATLAB中打印时可以看到回车。如果我让matlab在命令窗口中打印它,它的格式如下:

dataString =

'This is where the body of dataString goes.

There are not the same number of characters on

every line. Notice that MATLAB knows that there are

carriage returns interspersed throughout this text and

formats the output appropriately.

There are also numbers and other

types of characters in this array like 12, and %2

(m) %Z --- . When asked to print to the command window, MATLAB

treats all the contents of dataString as I want it to.

These contents need to be considered as generic as possible.

'

我希望能够使用fopen、fprintf和fclose来获取dataString的内容,并将它们放在具有相同属性的文本文件"genericTextFileName.txt"中当我在MATLAB中打印dataString时,每行打印出的字符也打印在文本文件的后续行上。当我执行以下操作时:

fileDirectory = 'C:UsersUniqueWorldlineDesktop'
[fid, errorMsg] = fopen(fileDirectory, 'w')
byteCount = fprinf(fid, '%s', dataString)
fcloseFile = fclose(fid)

dataString被打印到文本文件中,如下所示:

dataString =

'This is where the body of dataString goes. There are not the same number of characters on every line. Notice that MATLAB knows that there are carriage returns interspersed throughout this text and formats the output appropriately. There are also numbers and other types of characters in this array like 12, and %2 (m) %Z --- . When asked to print to the command window, MATLAB treats all the contents of dataString as I want it to. These contents need to be considered as generic as possible.'

基本上,dataString中存在的所有换行或回车格式都会丢失。删除"%s"没有帮助,因为fprintf认为"%"是一个特殊字符,我不能让它这样做,因为它会剪切第一个"%"之后的所有字符。我需要这种格式存在于文本文件中。在阅读了人们在fprintf和函数本身的文档中遇到的许多其他相关问题后,我找不到问题的答案。我该怎么做?

为什么会得到意外输出:

您提到的问题是操作系统和编辑器特有的。通常,Windows中的编辑器,如记事本,需要回车符r和换行符n。如果你在notepad++中打开文件,你确实会看到新行,就像在MATLAB的命令窗口中一样。

欲了解更多解释,请阅读以下文章:
‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍‍‍‍‍‍‍\n和\r之间的区别


解决方案:

对于编辑器,如文档中所述,您需要使用文本模式,在输出中的所有n之前插入一个r,同时使用fopen打开文件。即

[fid, errorMsg] = fopen('file.txt', 'wt');   %Notice wt

最新更新