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

Ignoring special characters while preserving formatting with MATLAB's fprintf function

我在名为 "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 中打印时在文本中有特定点可以看到回车符 return。如果我要求 matlab 在命令 Window 中打印它,它的格式如下:

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:\Users\UniqueWorldline\Desktop'
[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 中存在的所有新行或回车 return 格式都将丢失。删除 '%s' 没有帮助,因为 fprintf 然后将 '%' 视为特殊字符,我不能让它这样做,因为它会在第一个 '%' 之后删除所有内容。我需要这种格式存在于文本文件中。在阅读了人们对 fprintf 的许多其他相关问题和函数本身的文档之后,我找不到问题的答案。我该怎么做?

为什么会出现意外输出:

您提到的问题是 OS 和编辑器特定的。通常 Windows 中的编辑器,如记事本,需要回车 return 字符 \r 和换行符 \n。如果您在记事本++中打开该文件,您确实会看到新行,就像在 MATLAB 的命令 window 中一样。

有关更多说明,请阅读此 post:
‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ Difference between \n and \r?


解决方案:

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

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