word_cloud.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. import time
  3. from wordcloud import WordCloud, STOPWORDS
  4. from django.conf import settings
  5. from gauth.models import Location
  6. from review.models import Review
  7. from facebook_app.models import FacebookReview
  8. WC = WordCloud(
  9. width=1200,
  10. height=300,
  11. background_color='white',
  12. stopwords=STOPWORDS
  13. )
  14. GOOGLE_PATH = os.path.join(settings.BASE_DIR, 'media', 'google')
  15. FACEBOOK_PATH = os.path.join(settings.BASE_DIR, 'media', 'facebook')
  16. def create_wc_for_google(location_id):
  17. reviews = Review.objects.filter(location_id=location_id).exclude(comment=None)
  18. pos_reviews = reviews.filter(star_rating__gte=4)[:100]
  19. neg_reviews = reviews.filter(star_rating__lte=3)[:100]
  20. pos_text = ' '.join([review.comment for review in pos_reviews])
  21. neg_text = ' '.join([review.comment for review in neg_reviews])
  22. if len(pos_text) == 0:
  23. pos_text = "No positive Review found."
  24. if len(neg_text) == 0:
  25. neg_text = "No negative Review found."
  26. wc = WC.generate_from_text(pos_text)
  27. wc.to_file(GOOGLE_PATH+'/positive/'+f'{location_id}.png')
  28. wc = WC.generate_from_text(neg_text)
  29. wc.to_file(GOOGLE_PATH+'/negative/'+f'{location_id}.png')
  30. def create_wc_for_facebook(location_id):
  31. reviews = FacebookReview.objects.filter(page__location_id=location_id).exclude(review_text=None)
  32. pos_reviews = reviews.filter(recommendation_type=True)[:100]
  33. neg_reviews = reviews.filter(recommendation_type=False)[:100]
  34. pos_text = ' '.join([review.review_text for review in pos_reviews])
  35. neg_text = ' '.join([review.review_text for review in neg_reviews])
  36. if len(pos_text) == 0:
  37. pos_text = "Didn't found posted any positive Review."
  38. if len(neg_text) == 0:
  39. neg_text = "Didn't found posted any negative Review."
  40. wc = WC.generate_from_text(pos_text)
  41. wc.to_file(FACEBOOK_PATH+'/positive/'+f'{location_id}.png')
  42. wc = WC.generate_from_text(neg_text)
  43. wc.to_file(FACEBOOK_PATH+'/negative/'+f'{location_id}.png')
  44. def generate_word_clouds():
  45. locations = Location.objects.all()
  46. start = time.time()
  47. for loc in locations:
  48. create_wc_for_google(location_id=loc.location_id)
  49. create_wc_for_facebook(location_id=loc.location_id)
  50. end = time.time()
  51. print('Elapsed time: ', end-start, 'millisecond.')