stats.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. from pymongo import MongoClient, errors, DESCENDING, ASCENDING
  2. from bson.objectid import ObjectId
  3. import datetime
  4. import re
  5. import news
  6. import pytz
  7. import time
  8. from pprint import pprint
  9. class stats():
  10. DB = "alexis"
  11. def __init__(self):
  12. self.client = MongoClient('localhost', 27017)
  13. self.c_sources = self.client[self.DB]["sources"]
  14. self.c_articles = self.client[self.DB]["articles"]
  15. def jsonable(self, el):
  16. if el is None or "_id" not in el:
  17. return el
  18. el["_id"] = str(el["_id"])
  19. return el
  20. def sources_month(self, d, period):
  21. article_filter = {}
  22. article_filter['scrap_date'] = {'$gt': d - period}
  23. fields = {"source": 1}
  24. sources = [ p for p in self.c_sources.find({},{'name':1}) ]
  25. res = self.c_articles.find(article_filter, fields)
  26. ret = {}
  27. for s in sources:
  28. source = str(s['_id'])
  29. if source not in ret:
  30. ret[source] = 0
  31. for p in res:
  32. if p['source'] in ret:
  33. ret[p['source']] += 1
  34. else:
  35. ret[p['source']] = 1
  36. realret = {}
  37. for s in sources:
  38. source = str(s['_id'])
  39. realret[s['name']] = ret[source]
  40. for l in self.dict_to_csv(realret):
  41. print(l)
  42. return ret
  43. def sources(self, id=None):
  44. if id is None:
  45. return [self.jsonable(p) for p in self.c_sources.find()]
  46. ret = self.c_sources.find_one({"_id": ObjectId(id)})
  47. return self.jsonable(ret)
  48. def rss_sources(self):
  49. return [p for p in self.c_sources.find({"rss": 1})]
  50. def get_keywords_list(self):
  51. kw = self.client[self.DB]["keywords"]
  52. return [k["keyword"] for k in kw.find({})]
  53. def keywords_count(self):
  54. kw = {}
  55. for a in self.c_articles.find({'matches':True},{'kw':1}):
  56. if 'kw' not in a:
  57. print(a)
  58. continue
  59. for k in a['kw']:
  60. if k in kw:
  61. kw[k] += 1
  62. else:
  63. kw[k] = 1
  64. return kw
  65. def dict_to_csv(self, kv):
  66. ret = []
  67. for key in kv:
  68. ret.append('"%s",%s' % (key, kv[key]))
  69. return ret
  70. if __name__ == '__main__':
  71. s = stats()
  72. #for line in s.dict_to_csv(s.keywords_count()):
  73. # print(line)
  74. s.sources_month(datetime.datetime.today(), datetime.timedelta(1))
  75. s.sources_month(datetime.datetime.today(), datetime.timedelta(2))
  76. #for source in s.sources():
  77. # print(source['name'])