필터 지우기
필터 지우기

How to read text strings and count them

조회 수: 9 (최근 30일)
Aravin
Aravin 2015년 4월 20일
댓글: Guillaume 2015년 4월 20일
Hello All,
Lets assume I have one file which contains strings. I want to read that file, and create a matrix of word count/line. For example, I define I will have 5 words in file, which are
"we, are, you, people, student"
and the text file contains following three lines.
we are people and we are students you are students and people
Now I want matrix
we, are, you, people, student
line 1 2 2 0 1 1
line 2 0 1 1 1 1
  댓글 수: 1
Adam
Adam 2015년 4월 20일
doc textscan
doc strtok
doc strcmp
doc ismember
should help you (one or other of strcmp or ismember rather than both), though I don't have time to give a more detailed answer so just a comment. Someone else may provide a more detailed answer if you cannot work out the right combination of those functions.

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

채택된 답변

Guillaume
Guillaume 2015년 4월 20일
편집: Guillaume 2015년 4월 20일
One fairly simple way:
searchwords = {'we', 'are', 'you', 'people', 'student'}; %list of words to search
filecontent = fileread('somefile.txt'); %read whole text file
filelines = regexp(filecontent, '\r?\n', 'split'); %split lines
filewords = regexp(filelines, '[^a-zA-Z]+', 'split'); %split each line into words
wordcount = zeros(numel(filelines), numel(searchwords));
for line = 1:numel(filelines)
wordcount(line, :) = cellfun(@(searchword) sum(strcmp(filewords{line}, searchword)), searchwords);
end
  댓글 수: 2
Aravin
Aravin 2015년 4월 20일
Perfectory what I wanted. In addition, could you please tell how could I create searchwords by input file. For example, from file each word should be obtained and than their count matrix should be calculated.
Now I will have only file somefile.txt and the search words should be
{'and', 'are', 'you', 'people', 'student', 'we'}
Guillaume
Guillaume 2015년 4월 20일
To get the the unique list of words in the file, after it's been split into words:
searchwords = unique([filewords{:}]);
Note that I've edited my answer to improve the regular expression that splits the lines into words (it now ignores consecutive non-letters).

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by