Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Word Count 1

Status
Not open for further replies.

BlindPete

Programmer
Jul 5, 2000
711
US
Hello,

Is there a function to perform a word count, or count the occurences of string w/i a field? I really thought it was simple, but after an hour with the documentation and searching here. I'm stumped :-(

Thanks in advance.

-Pete
 
This is really pretty weak, I'm sure there are holes in it, but this expression in the SELECT statement works:
Code:
 1+(textvalue REGEXP " ") as wordcount

-Pete
 
It may be too thin ...


mysql> select fullname from myusers where usename='test';
+------------------------+
| fullname |
+------------------------+
| mary had a little lamb |
+------------------------+
1 row in set (0.00 sec)

mysql> select 1+(fullname REGEXP " ") as wordcount from myusers where usename='test';
+-----------+
| wordcount |
+-----------+
| 2 |
+-----------+
1 row in set (0.00 sec)


______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
Drat, your correct, that just parses the string, i made it more complex to include newlines and tabs but the result was no better. I'm not very good with REGEXP. Thanks for finding the hole.
Code:
1+(textvalue REGEXP "[.,:;?! \t\n]+") as wordcount

Is no better ;-(

I'll browse some regexsites and see what I can find.

-Pete
 
How about the following:

To count the number of spaces, which is (possibly) the word count minus 1:[tt]
SELECT
LENGTH(textfld)-LENGTH(REPLACE(textfld,' ',''))
[/tt]
To count occurrences of any string:[tt]
SELECT LENGTH(textfld)-LENGTH(REPLACE(textfld,'apple','****'))
[/tt]
Or, for flexibility:[tt]
SET @s:='apple';
SELECT
LENGTH(textfld)
-LENGTH(REPLACE(textfld,@s,REPEAT('*',LENGTH(@s)-1)))
[/tt]
 
um, i think the OP wants the number of certain words appearing in a string... like:

[tt]"data is stored in a data base even though i think data base is one word: database."[/tt]

should yield [tt]3[/tt] when doing a word count for "[tt]data[/tt]".

*cLFlaVA
----------------------------
[tt]I already made like infinity of those at scout camp...[/tt]
beware of active imagination: [URL unfurl="true"]http://www.coryarthus.com/[/url]

[banghead]
 
thats what i needed. why the heck i went down the REGEXP path I have no idea. Especially when the answer was so obvious. A star for you!

-Pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top