Reading a file containing words and converting to numerical values

I have a file by name test_sents.txt, it contains 3 sentences, I read the three sentences. Now, I have to take the first sentence and read each word in the sentence. Suppose my sentence is 'Cat threw the ball', my aim is to store the sentence in a variable X, now suppose I access X(1), it should give me Cat, if I access X(2), it should give me threw. I'm attaching the file (test_sents.txt) containing the sentences to this post. Can someone please help me in solving this problem?

Answers (1)

S = fileread('test_sents.txt');
S = regexprep(S, '\s*\r?\n\s*', ''); %get rid of line breaks and the blanks around them
sentences = regexp(S, '\s*\.\s*', 'split');
sentences( cellfun(@isempty, sentences) ) = [];
X = regexp(sentences, '\s+', 'split');
Now you have X{1}{1}, X{1}{2}, ... X{1}{13], X{2}{1} ... X{2}{9} and so on.

2 Comments

When I use the code as mentioned above I'm getting some error like 'Invalid option for regexp: split .'
The 'split' option was added in R2008a. If you are using an old version of MATLAB you need to tell us which version you are using so that we can advise you on something that will work for your release.
(*Why* are you using such an old version of MATLAB? The questions you are asking suggest you are a student.)

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!