CLEX420
CLEX420

Reputation: 31

How to count repeated words from the list

I have a list of cells,

  1. U1864
  2. u_dhm_lut/U4
  3. u_dhm_lut/lut_out_reg_2_
  4. u_dhm_lut/lut_in_reg_2_

And I want to calculate how many times each name comes Result will:

  1. U1864 1
  2. u_dhm_lut/lut_out_reg_2_ 18
  3. u_dhm_lut/lut_in_reg_2_ 14
  4. u_dhm_lut/U4 10

The code is like:

set cell_cnt [open "demo.txt" r]
set cell [read  $cell_cnt]
set b [open "number_of_cell.txt" w+]

proc countwords {cell_count} {
set unique_name [lsort -unique $cell_count]
foreach count $unique_name {
set cnt 0
foreach item $cell_count {
if {$item == $count} {
incr cnt
}
}
puts $b "$count :: $cnt"
}
}

countwords $cell

It says can't read "b":no such variable while executing "puts $b "$count :: $cnt"" Why am i not able write a file inside proc?

Upvotes: 0

Views: 1617

Answers (2)

Peter Lewerin
Peter Lewerin

Reputation: 13252

Code inside a procedure scope can't use variables defined outside that scope, e.g. global variables. To be able to use global variables, you can import them into the procedure scope:

proc countwords cell_count {
    global b

or use a qualified name:

puts $::b ... 

You can also bypass the issue by passing the file handle to the procedure:

proc countwords {b cell_count} {

... 

countwords $b $cell

or move the code for opening the file inside the procedure (not recommended: procedures should have one job only).

Old answer, based on the question title

This is one of the most frequently asked frequently asked questions. If you look a while back in the question list, you will find quite a few answers to this.

The solution is actually pretty easy, and the core of it is to use an array as a frequency table, with the words as keys and the frequencies as values. The incr command creates new entries (with a value of one) in the table as needed.

foreach word $words {
    incr count($word)
}

The result is similarly easy to check:

parray count

The result can of course also be used in a script in any way that an array can be used.

Documentation: array, foreach, incr, parray

Upvotes: 1

Anuj Gupta
Anuj Gupta

Reputation: 135

You can use the open file code i.e "set b [open "number_of_cell.txt" w+]" inside the method. This should also solve your problem

Upvotes: 0

Related Questions