|
| 1 | +from collections import namedtuple |
| 2 | + |
| 3 | +Tweet = namedtuple('Tweet', 'text polarity') |
| 4 | + |
| 5 | +# polarity < 0 = negative, > 0 = positive |
| 6 | +# long strings and pep8: you can wrap strings in () to reduce line length |
| 7 | +tweets = [ |
| 8 | + Tweet(text=("It's shocking that the vast majority of online banking " |
| 9 | + "systems have critical vulnerabilities leaving customer " |
| 10 | + "accounts unprotected."), |
| 11 | + polarity=-0.3333333333333333), |
| 12 | + Tweet(text=("The most unbelievable aspect of the Star Trek universe " |
| 13 | + "is that every ship they meet has compatible video " |
| 14 | + "conferencing facilities."), |
| 15 | + polarity=0.125), |
| 16 | + Tweet(text=("Excellent set of tips for managing a PostgreSQL cluster " |
| 17 | + "in production."), |
| 18 | + polarity=1.0), |
| 19 | + Tweet(text=("This tutorial has a great line-by-line breakdown of how " |
| 20 | + "to train a pong RL agent in PyTorch."), |
| 21 | + polarity=0.8), |
| 22 | + Tweet(text="This is some masterful reporting by ... It's also an " |
| 23 | + "infuriating story. ... is trying to erase debt by preying " |
| 24 | + "on the city’s residents. The poorest get hit the worst. " |
| 25 | + "It’s shameful.", |
| 26 | + polarity=-0.19999999999999998), |
| 27 | +] |
| 28 | + |
| 29 | + |
| 30 | +def filter_tweets_on_polarity(tweets, keep_positive=True): |
| 31 | + """Filter the tweets by polarity score, receives keep_positive bool which |
| 32 | + determines what to keep. Returns a list of filtered tweets.""" |
| 33 | + return list(filter(lambda x: (x.polarity > 0) == keep_positive, tweets)) |
| 34 | + |
| 35 | + |
| 36 | +def order_tweets_by_polarity(tweets, positive_highest=True): |
| 37 | + """Sort the tweets by polarity, receives positive_highest which determines |
| 38 | + the order. Returns a list of ordered tweets.""" |
| 39 | + sorted_tweets_positive = sorted(tweets, key=lambda x: x.polarity, reverse=positive_highest) |
| 40 | + return list(sorted_tweets_positive) |
0 commit comments