Home > OS >  Python List count() using a class and text file
Python List count() using a class and text file

Time:11-24

I am a beginner at python and have a question.

I have 2 text files:

The first one contains a schedule for programs:

------------------------------------------------------------------
Channel 1
16.00-17.45 Matinee: The kiss on the cross
17.45-17.50 The stock market today
------------------------------------------------------------------
Channel 2
8.30-9.00 The mosquito
9.00-10.00 Tip
17.50-18.20 In the company of dead masters
------------------------------------------------------------------
Channel 3
15.35-17.05 The weaker sex
17.05-18.00 The Onedine line
18.00-18.30 Children's trio: Dastardly & Mutley

I have created a class and managed on my own to create instances that look like this:

print(program_instances)

returns for example:
Channel 1, start:16.00 end:17.45 name:Matinee: The kiss on the cross 
Channel 1, start:17.45 end:17.50 name:The stock market today 
...

Then I have another text file with "viewer data":

File which contains data for one day collected from the TV sets included in the survey.
When the TV is switched on, it registers the time and tuned channel at fixed times every
day. Data from different devices is in the same file, but separated by dashed lines.

    Format: time/channel                
=================
19.37/2
19.52/2
21.07/1
21.22/1
21.37/1
-------
16.22/4
16.37/4
16.52/4
17.07/4
17.22/4
17.37/4
17.52/4
19.37/2
19.52/2
...

from this file, I want to calculate:

  • How many times the TVs were switched on to that specific channel.
  • The percentage of viewers from the total amount of data.
  • The total amount of TV’s separated by dashed lines

ex. I want to be able to print a top 10 list:

--------------------- top 10 ------------------- 
1. program 1: 57 times (60%)
2. program 2: 47 times(49%)
3. program 3: 34 times (36%)
...

Data was collected from #number of TV’s

I'm having trouble deciding how to do when reading and calculating the second file.

Could I use a list in my class to add/ append a '*' symbol each time a channel has a viewer? Then use the count() function to count the number of occurrences of the symbol for each list?

ex:

viewers = ['*','*','*','*','*','*']

My class looks like this:

def __init__(self,channel,start, end, name, viewers, percentage):
        self.channel = channel
        self.start = start
        self.end = end
        self.name = name
        self.viewers = viewers           #mabye use a list here?
        self.percentage = percentage

All help is much appreciated!

CodePudding user response:

You could create a list that accepts that channel number for each time the channel is switched on(the list looks like:[1,2,1,1,4,4....] then use the list.count(the channel num) function to return the number of times for each channel. so you will create a function that returns the value from the list and does other calculations

  • Related