Find a specific value in a csv file

조회 수: 11 (최근 30일)
Alexai
Alexai 2022년 7월 15일
댓글: Voss 2022년 7월 19일
How can I make it?
In csv file, I want to find the year in Part 1 and D value ("D":"1") in Part2
Finally I want to make :
2022, 1
2021, 2
2020, 3
2019, 4
2018, 5

답변 (2개)

Voss
Voss 2022년 7월 15일
Maybe this will work on your file (if not, upload the file here)
file_name = 'table_data.csv';
C = readcell(file_name,'Delimiter',',','NumHeaderLines',1);
years = regexp(C(:,1),'(\d{4})','tokens','once');
years = vertcat(years{:})
years = 5×1 cell array
{'2022'} {'2021'} {'2020'} {'2019'} {'2018'}
d = regexp(C(:,end),'D:"(\d+)"','tokens','once');
d = vertcat(d{:})
d = 5×1 cell array
{'1'} {'2'} {'3'} {'4'} {'5'}
% result as a cell array of character vectors:
result = [years d]
result = 5×2 cell array
{'2022'} {'1'} {'2021'} {'2'} {'2020'} {'3'} {'2019'} {'4'} {'2018'} {'5'}
% result as a numeric matrix:
result = str2double([years d])
result = 5×2
2022 1 2021 2 2020 3 2019 4 2018 5
  댓글 수: 9
Alexai
Alexai 2022년 7월 19일
편집: Alexai 2022년 7월 19일
um. sorry I have a mistake I want to read next slash ex)A/B/C0001/123456/abc0011
Thanksfully you give me a code
years = regexp(C(:,1),'/(\d{4})','tokens','once'); but I want to read next slash 123456->abc0011 How can I revise this code?
Voss
Voss 2022년 7월 19일
file_name = 'table_data.csv';
C = readcell(file_name,'Delimiter','\t','NumHeaderLines',1)
C = 5×2 cell array
{'A/1/2/AB0000/2022abc'} {'"B":"1", "C":"2", "D":"1"'} {'A/1/2/AB0000/2021abc'} {'"B":"1", "C":"2", "D":"2"'} {'A/1/2/AB0000/2020abc'} {'"B":"1", "C":"2", "D":"3"'} {'A/1/2/AB0000/2019abc'} {'"B":"1", "C":"2", "D":"4"'} {'A/1/2/AB0000/2018abc'} {'"B":"1", "C":"2", "D":"5"'}
years = regexp(C(:,1),'/([^/]*/[^/]*)$','tokens','once');
years = vertcat(years{:})
years = 5×1 cell array
{'AB0000/2022abc'} {'AB0000/2021abc'} {'AB0000/2020abc'} {'AB0000/2019abc'} {'AB0000/2018abc'}

댓글을 달려면 로그인하십시오.


Abderrahim. B
Abderrahim. B 2022년 7월 15일
Hi!
Try this:
% Create, split, and extract from part 1
part1 = "A/1/2/" + string(2022:-1:2018) ;
part1 = split(part1, '/') ;
yrs = part1(:,:,end) ;
% Create, split, and extract from part 2
part2 = " ""B"":""1"", ""C"":""2"", ""D"":""" + string(1:5) + '"' ;
part2 = split(part2, '"') ;
dig = str2double(part2(:,:,end-1)) ;
% Result
result = transpose(yrs + "," + dig )
result = 5×1 string array
"2022,1" "2021,2" "2020,3" "2019,4" "2018,5"
Use datetime if you want to convert this string array to date time array.
Please keep in mind this a way from many to solve it, you can also use regular experssion or patterns to do this.

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by