I need help counting the number of times a particular number is used in a text file...
and to output a number of results to a text file...

eg:
(input.txt):
01 40 39 01 72 39 36 56 72
82 39
###
56 62 38 03 03 06 38 30 42 ###

(output.txt):
read1:
39 = 3
01 = 2
72 = 2
36 = 1

read 2:
03 = 2
06 = 1


### = end/restart count

can anyone help??

Edited 6 Years Ago by Tcll: n/a

well I know there's a better way than just using var01 through var99 and increasing the value on every instance the var is assigned to...
(using a 'string = file.read(3)' type code)

that's an easy but time consuming code...

but I kinda need something before I go to bed today...

honestly...
I'm not the best with python even though it's my best code... (excluding html)

Edited 6 Years Ago by Tcll: n/a

Pseudocode

read whole file in variable

for parts using partition method
     for by words by split
         if word before in dictionary 
             add dictionary count 
         else assign dictionary count for word to 1
     output or save count for part

Edited 6 Years Ago by pyTony: n/a

sry for noobness...
I guess I'm still kinda new to py... :$

uhh... what's the partition method??

sry...
I never understood the tutorials...
I'm going by basic knowledge...
(you see my problem)

can anyone maybe show me an example code I can go by??

again, sry for the inconvienience :icon_redface:

You will also want to know how to do tonyjv's lines 5, 6, 7

  • The very best way is to use collections.Counter if you have it in your version of Python. Discover whether you do by trying to do this: from collections import Counter If it works, you are golden, and your code looks like this
    from collections import Counter
    numcounter = Counter()
    for line in readlines(theOpenedInputFile):
      numcounter.update(line.split())
      # numcouner.keys() is the set of distinct numbers seen
  • Without collections.Counter , there is an obvious way:
    #split each line into words and work one word at a time:
    if word in countDictionary:
      countDictionary[word] += 1
    else:
      countDictinary[word] = 1
  • Or you can use setdefault :
    countDictionary.setdefault(word,0)
    countDictionary[word] += 1

I'm sorry...

I'm just not getting it... :icon_confused:

I guess I'm just gonna go with the long way...
it's the only way I can actually think of to program...

thanx for the help though and I will look back on this :icon_smile:

Edited 6 Years Ago by Tcll: n/a

This article has been dead for over six months. Start a new discussion instead.