【问题标题】:How to sort lines of a text file by first word?如何按第一个单词对文本文件的行进行排序?
【发布时间】:2023-03-09 05:20:01
【问题描述】:

我有一个这种格式的 .txt 文件:

22 BLBL asas saaa212 x:12 y:123
66 BLadsBL asas saaa212 x:12 y:123
32 BLadsBL asas saaa212 x:13212 y:123
66 BLadsBL asas saaa212 x:1332 y:123

如何创建一个新的 .txt 文件,这些行按第一个值排序?

【问题讨论】:

  • Ps 我不关心速度,只关心最简单的代码
  • 为了以后,请避免用不相关的语言标记一些东西。
  • 是的,我做到了,我这样做是通过保留已用行的索引并一次又一次地运行文件(并进行 intecept),但这是非常丑陋的代码,我希望有人能给我一些想法,我不希望代码只是一种正确的思考方式
  • 你是如何阅读文件的?每行是一个字符串,还是将其分成不同的字段?它们是在数组、元胞数组、结构、表格还是其他东西中?您要按第一个 word 还是第一个 value 排序?例如第一行会按22BLBL 排序吗?你看过sortsortrows吗?

标签: matlab


【解决方案1】:
inpfid = fopen('InputFile.txt'); %This .txt file contains the data you gave in the question
allData = textscan(inpfid,'%s','Delimiter','\n');
% Read in the first word from each row of data
outcellarray = regexp(allData{:},'^([\w\-]+)','match');
% Store all the first numbers into a single cell array and sort them
[~, ind] = sort(str2double(vertcat(outcellarray{:})));
% Creating a cell with the required order
output = cellfun(@(x) x(ind), allData, 'UniformOutput', 0);
% Making it into a form useable for writing a text file
output= output{:}; 

outfid=fopen('OutputFile.txt','wt+'); %Creating an output file
for k = 1:length(output)-1
  %Writing the data
  fprintf(outfid,output{k});
  fprintf(outfid,'\n');
end
fprintf(outfid,output{end});
% You can loop from 1 to length(output) and skip the last line 
% but it'll append an extra line at the end of the output file
fclose(outfid); % Closing the output file

输入输出文件对比:


附注:
✶ 确保输入和输出文件都位于当前路径或提供完整路径,例如:'D:\Assignment\InputFile.txt'

✶ 我使用/复制了以下代码/想法:
https://stackoverflow.com/a/23357800/5698672
https://stackoverflow.com/a/5041474/3293881
https://stackoverflow.com/a/28348768/5698672
所以,如果这些答案能解决您的问题,也请给这些答案投票。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2023-04-10
    • 2019-06-25
    相关资源
    最近更新 更多