Creating character codes from text file
1 view (last 30 days)
Show older comments
Suppose that I have a text file contains several lines such as the following
My name is John, I studied Chemistry at Okawata University. I am a Canadian citizen but I lived in 123
I want to do the following:
- I want to remove all punctuation marks fro the text.
- I want to convert the remaining character including the spaces and the numbers into predefined codes such as: (A: c01, B: c02, ... , a:c27. b:c28) ans also the numbers such as (0:c60, 1:c60, 2:c61) and store the results into another output text file which contains only the codes and each character in a line as follows (suppose the code of the characters of the string "My name": M:c07, y:c30, space:c22, n:c35, ...) so the output file should contain:
c07
c30
c22
c35
..
0 Comments
Accepted Answer
Thorsten
on 23 Oct 2015
Edited: Thorsten
on 23 Oct 2015
Set up code table X
chars = ['A':'Z' 'a':'z'];
for i = 1:numel(chars)
X{chars(i)} = sprintf('c%02d', i);
end
digits = '0':'9'
for i = 1:numel(digits)
X{digits(i)} = sprintf('c%02d', 59+i);
end
X{' '} = 'c22';
Encode string
s = 'My name is John, I studied Chemistry at Okawata University.';
sc = strvcat(X{'My name is John.'})
Note that you don't have to remove the punctuation marks, they are mapped to empty and removed my strvcat.
3 Comments
More Answers (1)
dpb
on 23 Oct 2015
- is pretty straightforward to replace characters with empty, thereby removing them entirely. regexp is one way
- build a "lookup table" of the code desired for each character stored in its ASCII collating sequence. IOW, using your example above for a small subset, since
>> s='My name';
>> double(s)
ans =
77 121 32 110 97 109 101
>>
store the codes for each of those in those array elements.
Then, since Matlab will do an automagic conversion from character to numeric, you can do the conversion on any converted string simply by
codedstr=codearray(cleanedInputString).';
and you're done...
I'll leave the intimate details as "exercise for student"... :)
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!