parser.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/python3
  2. import sys
  3. import re
  4. import newspaper
  5. import pymongo
  6. from frontpage import FrontPage
  7. from newspaper import Article
  8. from pymongo import MongoClient
  9. class db():
  10. def __init__(self):
  11. self.client = MongoClient('localhost', 27017)
  12. self.col=self.client.alexis["sources"]
  13. def sources(self):
  14. return [ p for p in self.col.find({"rss":0}) ]
  15. def rss_sources(self):
  16. return [ p for p in self.col.find({"rss":1}) ]
  17. class LinkList():
  18. def __init__(self,url,selector=None):
  19. if selector is None:
  20. s=newspaper.build(url)
  21. print(url)
  22. for a in s.articles:
  23. print(a)
  24. else:
  25. f=FrontPage(url,selector)
  26. self.links=f.links
  27. # def getList(self):
  28. # ret=[]
  29. # for art in self.source.articles:
  30. # print(art)
  31. # print(art.url)
  32. # ret.append(art.url)
  33. # return ret
  34. class News():
  35. r=re.compile(r"hours? ago|yesterday|today|last week|month",flags=re.IGNORECASE)
  36. def __init__(self,url):
  37. a = Article(url, language='en')
  38. a.download()
  39. a.parse()
  40. a.nlp()
  41. a.authors=self.dedup([self.fix_author(value) for value in a.authors if not self.isComment(value)])
  42. print(a.authors)
  43. print(a.publish_date)
  44. print(a.summary)
  45. print(a.keywords)
  46. #print(a.text)
  47. print(a.top_image)
  48. print(a.movies)
  49. def dedup(self,val):
  50. return list(set(val))
  51. def isComment(self,v):
  52. if self.r.match(v):
  53. return True
  54. return False
  55. def fix_author(self,a):
  56. return a.replace("_", " ").lower()
  57. d=db()
  58. def sanitizeSelector(s):
  59. s=s.replace(">a","> a")
  60. if re.match(r'=\w+\]',s) is None:
  61. return s
  62. print(s)
  63. ret=re.sub(r"=(\w+)]", r'="\1"]', s)
  64. print(ret)
  65. return ret
  66. for s in d.sources():
  67. s["title"]=sanitizeSelector(s["title"])
  68. l=LinkList(s["link"],s["title"])
  69. if len(l.links)==0:
  70. print(s["link"])
  71. print(s["title"])
  72. print("###################################")
  73. #n=News("http://www.bloomberg.com/news/articles/2016-03-04/the-mystery-madoff-victims-who-left-2-5-billion-on-the-table")