Script to count word occurrences, but exclude some?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Script to count word occurrences, but exclude some?
# 1  
Old 06-15-2012
Script to count word occurrences, but exclude some?

I am trying to count the occurrences of ALL words in a file. However, I want to exclude certain words: short words (i.e. <3 chars), and words contained in an blacklist file. There is also a desire to count words that are capitalized (e.g. proper names). I am not 100% sure where the line on capitalization is; i.e. do we count the first word of a sentence differently? What if it is a word that would be capitalized in the middle of a sentence, e.g. a name? So working on the other parts is more important, but any other input would be appreciated.

I have put together a command to do the word counting in the file (I borrowed code that I found here in other postings). It is in a script here, and uses command line arguments for the filename, too:

Code:
tr -cs "[:alpha:]'" "\n" < $1 | sort | uniq -c | sort -rn >w_counts.txt

In the TR command, I have put in an apostrophe in the match set so that it doesn't break up contractions (e.g. "doesn't"). The output of TR is a CR/LF separated list of words that is then fed into the others, where it gets sorted so that 'uniq' will count correctly. Then that is reverse sorted (we want to know about the highest occurring words) and output to the text file. (This will eventually be imported back into a database.)

This works in about .5 seconds on a 4000+ word file. I am pretty happy with that. Smilie

Any comments or suggestions about excluding short words or words from a blacklist file, or even the counting capitalized words, would be appreciated.

I am working on Mac OS X 10.6.8, but would hope to get a solution that will work under a Windows Unix-like shell (e.g. Cygwin).


Thanks,
J
# 2  
Old 06-15-2012
Given your requirements for black listing and finding capitalised leading letters, I'd probably have approached it this way:

Code:
awk '
    NR == FNR { $1; blist[$1]; next; }      # read black list

    {
        for( i=1; i <= NF; i++ )
        {
            ignore = ignore_nxt;
            ignore_nxt = 0;
            ignore_nxt = ( match(  $i, "[?.!]" ) && RSTART == length( $i ) );

            gsub( "[:,%?<>&@!=+.()]", "", $(i) );       # trash punctuation not considered part of a word
            if( length( $(i) ) > 3 )
            {
                count[$(i)]++;
                fc = substr( $(i), 1, 1 );
                if( !ignore && fc >= "A" && fc <= "Z" )
                    cap++;
            }
        }
    }
    END {
        printf( "words starting with a capital: %d\n", cap ) >"/dev/fd/2";  # out to stderr so it doesnt sort
        for( x in count )
        {
            if( !( x in blist ) )
                print x, count[x];
        }
    }
' blacklist.file text-file | sort -k 2nr,2

The captialisation is tricky. You can count all words with capitalised letters, or ignore those that immediatly follow a full stop (.), question (?) or explaination (!). The code above does the latter -- effectively counting proper names that appear in the middle of the sentence. You can comment out the statements that check for and set the ignore variables, and it will count all words that start with a capitalised letter and are larger than 3 characters in length.

Might not be exactly what you want, but it should give you an idea of one method.
This User Gave Thanks to agama For This Post:
# 3  
Old 06-16-2012
Uff da! Quite a bit of code there; thanks for taking the time to put that together.

If the task of figuring out capitalization is ignored, is there something else you might suggest to handle excluding short words, or incorporating a black list? I like the one liner shell commands. Smilie

Thanks,
J
# 4  
Old 06-16-2012
Hi


Code:
$ cat file
hi hello world
welcome to india
welcome to unix.com

Code:
$ cat black
world

Code:
$ sed -r 's/ +/\n/g' file | grep -v -f black | awk 'length>3{a[$0]++}END{for(i in a)print i, a[i];}'
hello 1
india 1
welcome 2
unix.com 1

Guru.
# 5  
Old 06-16-2012
I would take a slightly different approach. No need for the leading sed, and I would exclude the black list on the output of the awk assuming that will be a shorter list than the output of an initial sed. I'd also strip punctuation/special characters so that something like (word is counted as word without the paren. I'd also check the length after removing specials/punct so that (and is dropped if you want only words that have a length greater than 3.

This can be smashed onto one line, but it's easier to read and commented when written with some structure:

Code:
awk '
    BEGIN { RS = "[" FS "\n]" }         # break into records based on whitespace and newline (this may require gnu awk and not work in older versions)
    { 
        gsub( "[:,%?<>&@!=+.()]", "", $(i) );   # ditch unwanted punctuation before looking at len
        if( length( $0 ) > 3 )                  # keep only words long enough
            count[$0]++; 
    } 

    END {
        for( x in count )
            print x, count[x];
    }'  data-file | grep -v -f black-list |sort -k 2rn,2


Last edited by agama; 06-16-2012 at 01:06 PM.. Reason: clarification
# 6  
Old 06-18-2012
I was trying to implement part of your suggestions but ended up with a blank Results file. Here is what I am using:

Code:
time tr -cs "[:alpha:]'" "\n" < $1 | grep -v -f blacklist.txt | sort | uniq -c | sort -rn >counts.txt

The only added part is the 'grep -v -f ...' that you suggested. I created the blacklist text file, one word per line. Blacklist file is in the same directory as the shell script. (Seems like it would complain if it couldn't find it.)

Thanks,
J

---------- Post updated at 03:16 PM ---------- Previous update was at 02:31 PM ----------

Ah, I think I found an answer. Not exactly sure what the difference is, but it appears to work. Smilie (Remember, this is in a script and the $1 is the script parameter.)

Code:
time tr -cs "[:alpha:]'" "\n" < $1 | grep -viFf  blacklist.txt | sort | uniq -c | sort -rn >counts.txt

This also works (is apparently the same as the above?):
Code:
time tr -cs "[:alpha:]'" "\n" < $1 | fgrep -vif  blacklist.txt | sort | uniq -c | sort -rn >counts.txt

Now, why is it that :
"-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
"

appears to work the way that the "-f" option SOUNDS like it would work?

---------- Post updated at 04:22 PM ---------- Previous update was at 03:16 PM ----------

OK, I have figured out a bit further: matching only words of 3 or more characters:

Code:
time tr -cs "[:alpha:]'" "\n" < $1 | fgrep -vif  blacklist.txt | egrep '\w{3,}' | sort | uniq -c | sort -rn >counts.txt

I think that the only missing part is the whole capitalization issue. But that isn't a pressing issue, I don't think. And it still appears to be running in less than .03 seconds! Gotta love the shell sometimes.

Thanks all for your suggestions.

-- J
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

awk or sed script to count number of occurrences and creating an average

Hi Friends , I am having one problem as stated file . Having an input CSV file as shown in the code U_TOP_LOGIC/U_HPB2/U_HBRIDGE2/i_core/i_paddr_reg_2_/Q,1,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0... (4 Replies)
Discussion started by: kshitij
4 Replies

2. UNIX for Beginners Questions & Answers

UNIX script to check word count of each word in file

I am trying to figure out to find word count of each word from my file sample file hi how are you hi are you ok sample out put hi 1 how 1 are 1 you 1 hi 1 are 1 you 1 ok 1 wc -l filename is not helping , i think we will have to split the lines and count and then print and also... (4 Replies)
Discussion started by: mirwasim
4 Replies

3. Shell Programming and Scripting

Count occurrences in first column

input amex-11 10 abc amex-11 20 bcn amed-12 1 abc I tried something like this. awk '{h++}; END { for(k in h) print k, h }' rm1 output amex-11 1 10 abc amex-11 1 20 bcn amed-12 2 1 abc Note: The second column represents the occurrences. amex-11 is first one and amed-12 is the... (5 Replies)
Discussion started by: quincyjones
5 Replies

4. Shell Programming and Scripting

Word Occurrences script using awk

I'm putting together a script that will the count the occurrences of words in text documents. It works fine so far, but I'd like to make a couple tweaks/additions: 1) I'm having a hard time displaying the array index number, tried freq which just spit 0's back at me 2) Is there any way to... (12 Replies)
Discussion started by: ksmarine1980
12 Replies

5. Shell Programming and Scripting

Word Count In A Script

I am in need of a basic format to 1. list all files in a directory 2. list the # of lines in each file 3. list the # of words in each file If someone could give me a basic format i would appreicate it ***ALSO i can not use the FIND command*** (4 Replies)
Discussion started by: domdom110
4 Replies

6. Shell Programming and Scripting

How to count occurrences in a specific column

Hi, I need help to count the number of occurrences in $3 of file1.txt. I only know how to count by checking one by one and the code is like this: awk '$3 ~ /aku hanya poyo/ {++c} END {print c}' FS="\t" file1.txt But this is not wise to do as i have hundreds of different occurrences in that... (10 Replies)
Discussion started by: redse171
10 Replies

7. Shell Programming and Scripting

Count occurrences in awk

Hello, I have an output from GDB with many entries that looks like this 0x00007ffff7dece94 39 in dl-fini.c 0x00007ffff7dece97 39 in dl-fini.c 0x00007ffff7ab356c 50 in exit.c 0x00007ffff7aed9db in _IO_cleanup () at genops.c:1022 115 in dl-fini.c 0x00007ffff7decf7b in _dl_sort_fini (l=0x0,... (6 Replies)
Discussion started by: ikke008
6 Replies

8. Shell Programming and Scripting

Count the number of occurrences of the word

I am a newbie in UNIX shell script and seeking help on this UNIX function. Please give me a hand. Thanks. I have a large file. Named as 'MyFile'. It was tab-delmited. I am told to write a shell function that counts the number of occurrences of the ord “mysring” in the file 'MyFile'. (1 Reply)
Discussion started by: duke0001
1 Replies

9. UNIX for Dummies Questions & Answers

count occurrences and substitute with counter

Hi Unix-Experts, I have a textfile with several occurrences of some string XXX. I'd like to count all the occurrences and number them in reverse order. E.g. input: XXX bla XXX foo XXX output: 3 bla 2 foo 1 I tried to achieve this with sed, but failed. Any suggestions? Thanks in... (4 Replies)
Discussion started by: ptob
4 Replies
Login or Register to Ask a Question