Hello I am writing a python script to generate count of monthly and daily visits for web pages. Input file:
ArticleName Date Hour Count/Visit
Aa 20130601 10000 1
Aa 20130601 10000 1
Ew 20130601 10000 1
H 20130601 10000 2
H 20130602 10000 1
R 20130601 20000 2
R 20130602 10000 1
Ra 20130601 0 1
Ra 20130601 10000 2
Ra 20130602 10000 1
Ram 20130601 0 2
Ram 20130601 10000 3
Ram 20130602 10000 4
Re 20130601 20000 1
Re 20130602 10000 3
Rz 20130602 10000 1
I need to count total Monthly and Daily page views of each page.
Output:
ArticleName Date DailyView MonthlyView
Aa 20130601 2 2
Ew 20130601 1 1
H 20130601 2 2
H 20130602 1 3
R 20130601 2 2
R 20130602 1 4
Ra 20130601 5 5
Ra 20130602 1 6
Ram 20130601 5 5
Ram 20130602 4 9
Re 20130601 1 1
Re 20130602 3 4
Rz 20130602 1 1
My Script:
#!/usr/bin/python
import sys
last_date = 20130601
last_hour = 0
last_count = 0
last_article = None
monthly_count = 0
daily_count = 0
for line in sys.stdin:
article, date, hour, count = line.split()
count = int(count)
date = int(date)
hour = int(hour)
#Articles match and date match
if last_article == article and last_date == date:
daily_count = count+last_count
monthly_count = count+last_count
# print '%s\t%s\t%s\t%s' % (article, date, daily_count, monthly_count)
#Article match but date doesn't match
if last_article == article and last_date != date:
monthly_count = count
daily_count=count
print '%s\t%s\t%s\t%s' % (article, date, daily_count, monthly_count)
#Article doesn't match
if last_article != article:
last_article = article
last_count = count
monthly_count = count
daily_count=count
last_date = date
print '%s\t%s\t%s\t%s' % (article, date, daily_count, monthly_count)
I am able to get most of the output but my output is wrong for two condition: 1. Couldn't get a way to sum up the ArticleName if ArticleName and ArticleDate are same. For eg this script gives output for row Ra: Ra 20130601 1 1 Ra 20130601 3 3 Ra 20130602 1 1 So at the end Ra should print 1+3+1=5 as final total monthly count instead of 1.
- Since I display in the 3rd if condition all the articles which are not equal to last article I get the value of an article with same article name and date twice. Like:
Ra 20130601 1 1should not have been printed. Does anybody know how to correct this? Let me know if you need any more information.
R 20130602 1 4should beR 20130602 1 3?