how to define the occurance of a word in a text?

조회 수: 1 (최근 30일)
jojototo
jojototo 2017년 7월 28일
댓글: jojototo 2017년 8월 15일
Hi all,I need that code badly,I have a text'.txt'.I have chosen two words"are" and "the" which are repeated along the text so I need a code to read the text and if the word "are" comes put "1" and if the word "the" comes put "0" sequentially so a series of binary digits"x" is formed. for example x=1 0 0 1 1 1 1 0 that means "are" occurs first then "the"occurs twice then"are" four times then"the" and so on until the text ends.thanks
  댓글 수: 6
Walter Roberson
Walter Roberson 2017년 7월 30일
So not counted if there is a comma, period, exclamation mark, colon, semi-colon, apostrophe or double quote or other quote marks?
jojototo
jojototo 2017년 7월 31일
Oh my god,I didn't think about all these possibilities .You're absolutely right all these are counted of course.

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

채택된 답변

Walter Roberson
Walter Roberson 2017년 7월 30일
whichone = strcmp('and', lower(regexp(str, '(?<=^| )(([tT]he)|([aA]nd))(?=$| )', 'match')));
whichone is 1 for each occurrence of 'and' and 0 for each occurrence of 'the'
  댓글 수: 4
Walter Roberson
Walter Roberson 2017년 8월 9일
Break it up into pieces.
thes = regexp(str, '(?<=^|["'' ])([tT]he ?)(?=$|[,.!:;"'' ])');
this finds "the" or "The" that are preceded by beginning of line or by a space or double quote or apostrophe, and which might be followed by a space, and after that followed by a comma, period, exclamation mark, colon, semi-colon, double-quote, apostrophe, or space. The "the" or "The" and the possible space are extracted, but not what follows that.
Once you have these, you can tell the cases apart by various ways, including comparing the last character to a space, or just looking at the length:
cellfun(@length, thes)
length 3 has no space after it, length 4 had a space after it.
Unfortunately, though, you have an ambiguous situation. At the end of the line, you cannot tell whether "the" followed by space followed by end of line is the "normal" case or the "extra space" case. This code will detect it as if it is the "extra space" case, but that is arguably wrong: it could instead be a "normal space" that happens to be followed by nothing.
As I wrote before, "Rules! We need rules!" -- and those rules need to define what the "correct" outcome is in each potentially ambiguous situation.
jojototo
jojototo 2017년 8월 15일
Thanks a lot

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dialog Boxes에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by