map first field to second field in txt file
1 回表示 (過去 30 日間)
古いコメントを表示
hi,
I have this txt file :
1::Toy Story (1995) ::Animation|Children's|Comedy
2::Jumanji (1995) ::Adventure|Children's|Fantasy
8::Tom and Huck (1995) ::Adventure|Children's
I want to map for example 1 into animation, and 2 into adventure 8 into adventure i.e ,i need creat txtfile has two columns , the first column contains 1,2,8 and second column contains animation,adventure,adventure
please, how do that thanks in advance
0 件のコメント
採用された回答
per isakson
2012 年 7 月 31 日
編集済み: per isakson
2012 年 8 月 5 日
A slight modification of the textscan command I provided to your question the other day will read the file. (You never explained how "::" should be interpreted.) What do you mean by "I read each filed alone of a one row, textscan do not work with it."? If you don't need a column add "*" after "%", e.g. "%*d" to suppress the first column.
Thus
>> cac = txt2m
cac =
[3x1 int32] {3x1 cell} {3x1 cell}
>> cac{:}
ans =
1
2
8
ans =
'Toy Story (1995) '
'Jumanji (1995) '
'Tom and Huck (1995) '
ans =
'Animation|Children's|Comedy'
'Adventure|Children's|Fantasy'
'Adventure|Children's'
>>
where the function, txt2m, is given by
function cac = txt2m()
fid = fopen('cssm.txt');
cac = textscan( fid, '%d%s%s' ...
, 'Delimiter' , ':' ...
, 'CollectOutput' , false ...
... , 'EmptyValue' , -999 ...
... , 'ExpChars' , '' ...
, 'MultipleDelimsAsOne' , true ...
, 'Whitespace' , '' );
fclose( fid );
end
then regexp and str2num
>> regexp( cac{2}, '\d{4}', 'match' )
ans =
{1x1 cell}
{1x1 cell}
{1x1 cell}
>> ans{:}
ans =
'1995'
ans =
'1995'
ans =
'1995'
--- In response to the answer below ---
This modified function, txt2m, reads and parses your file. It reads the file to a string with the function, fileread (thanks Walter, I didn't know of that one), and replaces "::" by "¤" (knock on wood). I just picked a character on the keyboard.
Try
>> cac = txt2m()
cac =
[13x1 int32] {13x1 cell} {13x1 cell}
>>
where
cssm.txt contains your 13 rows
and where
function cac = txt2m()
str = fileread( 'cssm.txt' );
str = strrep( str, '::', '¤' );
cac = textscan( str, '%d%s%s' ...
, 'Delimiter' , '¤' ...
, 'CollectOutput' , false ...
... , 'EmptyValue' , -999 ...
... , 'ExpChars' , '' ...
, 'MultipleDelimsAsOne' , true ...
, 'Whitespace' , '' );
end
13 件のコメント
per isakson
2012 年 8 月 3 日
編集済み: per isakson
2012 年 8 月 3 日
- What did you do? What does your new code look like?
- How does it behave? What output? What error message?
Why do you expect me to guess?
その他の回答 (1 件)
huda nawaf
2012 年 8 月 4 日
編集済み: Walter Roberson
2012 年 8 月 4 日
3 件のコメント
per isakson
2012 年 8 月 4 日
編集済み: per isakson
2012 年 8 月 4 日
See my answer above. I hope the lines you don't show don't contain "¤".
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!