Skip to content

Instantly share code, notes, and snippets.

@Sebastian-Nielsen
Created March 16, 2018 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sebastian-Nielsen/1cbb695423768d96e024333f1144d0e4 to your computer and use it in GitHub Desktop.
Save Sebastian-Nielsen/1cbb695423768d96e024333f1144d0e4 to your computer and use it in GitHub Desktop.
from afinn import Afinn # https://github.com/fnielsen/afinn
from collections import namedtuple
afinn = Afinn(language='da', emoticons=True)
ScoreTuple = namedtuple('scores', 'score word line')
def sentiment_score_of_words(text, ignore_neutral_sentiment=True, show_analysis=True):
text = clean_text(text)
lineNr = 1
scores = []
lines = [line for line in text.split('\n')]
for line in lines:
for word in line.strip().split(' '):
if (ignore_neutral_sentiment and afinn.score(word) == 0):
continue
else:
scores.append( ScoreTuple(afinn.score(word), word, lineNr) )
lineNr += 1
if show_analysis:
for nTuple in sorted(scores, reverse=True):
print(f"{nTuple.score} \"{nTuple.word}\", linje: {nTuple.line}")
return scores
def sentiment_score_of_text(text, show_score=True):
text = clean_text(text)
score = afinn.score(text)
if show_score:
print(f"The text's score is: {score}")
return score
def clean_text(text):
"""Cleans the text from characters such as , . ! ? """
chars_to_clean = (',','.','!','?')
for c in chars_to_clean:
text = text.replace(c, '')
return text
if __name__ == '__main__':
text = """Dette er en dansk tekst, fyldt med positive og gode ord. Der er dog nogle dårlige og knap så
gode ord ind i mellem. Men overordnet set er teksten positivt ladet med fantastiske himmerigske ord."""
sentiment_score_of_words(text)
sentiment_score_of_text(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment