MATLAB 选项(部分测试)
我不得不用 CMM 做一次类似的事情,而且在 Python 中很容易做到(见下文)。您可以使用 MATLAB 命令regexp(text, expression) 来匹配得到您想要的正则表达式。不过,这将返回字符串数据,您可以将其保存到数据文件,然后load that data file,或使用str2double 转换为数字。
要使用它,您首先必须将您的数据文件作为一系列字符串放入 MATLAB。您可以使用fgetl 来执行此操作。
in_fid = fopen('my_input_file.txt', 'r');
out_fid = fopen('my_output_file.txt', 'w');
data = [];
line = fgetl(in_fid);
while ischar(line)
match = regexp(line, '[+-]?\d+\.?\d*e?[+-]?\d*', 'match'); % find all matches
% Write to text file
fprintf(out_fid, '%s\t', match); % write values to file with tabs between
fprintf(out_fid, '\n'); % write a new line to the file
% Or save to an array locally
data = [data; str2double(match)];
line = fgetl(in_fid); % grab the next line
end
fclose('all');
% If you wrote to a text file, retrieve the data
data = dlmread('my_output_file.txt', 'delimiter', '\t'); % not sure about this...
请注意,这将不匹配以小数点开头且前面没有数字的数字,即.2。另请注意,这将匹配与您提供的任何文件中的模式匹配的数字,因此它是通用的。关于如何匹配浮点数,see this site(我做了一点改动,添加了e 部分作为科学记数法)。
我能够在远程机器上测试regexp 和str2double 操作,看起来像直接构建数据数组一样有效。我无法测试文件 I/O 部分,因此可能仍然存在一些错误。
Python 选项(我最喜欢的)
我建议在 Python 中使用正则表达式来处理这类事情。我不得不用 CMM 做一次类似的事情,在 Python 中很容易做到,比如:
import re
# Make pattern to match scientific notation numbers
pattern = re.compile(r"[+-]?\d+\.?\d*e?[+-]?\d*")
with open("your_input_file.txt", "r") as in_file:
with open("your_output_file.txt", "w") as out_file:
for line in in_file:
match = pattern.findall(line) # find all matches in the line
out_file.write("\t".join(match) + "\n") # write the results to a line in your output
有关 Python 中正则表达式的良好介绍,请参阅 Dive Into Python 3,我建议几乎每个人都阅读。我在您的示例文件上对此进行了测试,它给了我:
1 1.3 -2.1 0 1.3e+0 -2.1e+0 1.4e-3 2.0e-3 -0.6 0.4
2 1.4 -2.1 0 1.4e+0 -2.1e+0 2.8e-3 1.5e-3 -0.6 0.4
3 -1.9 1.9 0 -1.9e+0 1.9e+0 -8.9e-2 1.4e-1 0.7 -0.2
在your_output_file.txt,所以我认为它有效!最后一步就是在 MATLAB 中输入 dlmread('your_output_file.txt', 'delimeter', '\t'),您应该一切顺利。
如果您想变得花哨,您可以升级您的 Python 脚本,以便可以从命令行调用它,并将您的输入和输出文件作为参数(查看 sys.argv 方法),但这会更多很复杂,只需打开脚本并手动更改文件名就很容易了。除非您需要一直对不同名称的文件执行此操作,在这种情况下,参数是一个很好的途径。 There is a good example of this here.