コード例 #1
0
 def runClassifier(self):
     result = []
     for tweet in self.feeds:
         if "text" in tweet:
             obj = {}
             sent = tweet["text"]
             print(sent)
             print(s.sentiment(sent))
             obj["id"] = tweet["id"]
             obj["category"] = s.sentiment(sent)[0]
         result.append(obj)
     return result
コード例 #2
0
def text_pass(paragraphs):
	out = []
	for p in paragraphs:

		# tokenized = nltk.word_tokenize(p['text'])
		# tagged = nltk.pos_tag(tokenized)
		# chunked = chunker.parse(tagged)
		# nps = list(chunked.subtrees(lambda t: t.label() == 'NP'))
		# save_nps = {' '.join([x for (x,y) in np.leaves()]) for np in nps}
		
		nps = nps_in_paragraph(p['text'])

		p['concepts'] = []

		sent_label = s.sentiment(p["text"])

		for np in nps[0]:
			# print(np)
			p['concepts'].append({'concept':np[0][0],'j':int(np[1]),'i':(int(np[1]) - len(np[0][0].split(' '))),'s':sent_label})

		# for n in save_nps:
		# 	starts = [m.start() for m in re.finditer(n.replace('[','').replace(']',''), p['text'])]
		# 	positions = [{'concept':n,'i':s,'j':s+len(n),'s':sent_label} for s in starts]
		# 	for pos in positions:
		# 		# print(pos)
		# 		if pos['concept'] != "[" and pos['concept'] != "]":
		# 			p['concepts'].append(pos)
		p['concepts'].sort(key=lambda c: c['i'])
		p['text'] = nps[1]
		out.append(p)
	return out
コード例 #3
0
ファイル: rate_opinion.py プロジェクト: atul46/the-code
def get_review_rate(appid):
    """
    This function only returns the review analysis result and word cloud.
    Doesn't store any results
    """
    for data in db[config.REVIEW_COLLECTION].find({'_id': appid}, {'latest_reviews':1, 'crawling_date':1}):
        #for data in db.snapv2_0.find({},{'latest_reviews':1, 'crawling_date': 1}):
        if len(data['latest_reviews']) < 35:
            continue
        data_dict = {}
        data_dict['_id'] = data['_id']
        data_dict['review_date'] = [ data['crawling_date'][-1] ]

        app_rev = data['latest_reviews']
        p_score = n_score  = 0
        p_rev = n_rev = ''

        for rev in app_rev:
            result = rate.sentiment(rev)[0]
            if result == 'pos':
                p_score += 1
                p_rev += rev
            elif result == 'neu':
                pass
            else:
                n_score += 1
                n_rev += rev

        #calculate the score
        data_dict['p_percent'] = p_score / ( p_score + n_score )
        data_dict['n_percent'] = n_score / ( p_score + n_score )
        #counter with most common 20 words
        data_dict['positive_cloud'] = Counter([w for w in p_rev.lower().split() if w not in stop_words and len(w) > 2]).most_common(20)
        data_dict['negative_cloud'] = Counter([w for w in n_rev.lower().split() if w not in stop_words and len(w) > 2]).most_common(20)
        return data_dict
コード例 #4
0
ファイル: twitter.py プロジェクト: cosmos-sajal/NLTK
    def on_data(self, data):
      all_data = json.loads(data)
      tweet = all_data["text"]
      sentiment_value, confidence = s.sentiment(tweet)
      print(tweet, sentiment_value, confidence)

      if confidence*100 >= 80:
        output = open("twitter-out1.txt","a")
        output.write(sentiment_value)
        output.write('\n')
        output.close()
      return True
コード例 #5
0
def classify_tweets(language):
  input_lang = language[0].lower()

  vw_original = pd.read_csv('output/vw_clean_' + input_lang + '_rechecked.csv')
  vw = pd.DataFrame(data=vw_original)

  vw_out = pd.DataFrame(columns=['id', 'classification'])

  for index, row in vw.iterrows():
    try:
      if len(str(row['text']).split()) > 1:
        print (s.sentiment(str(row['text'])))
        vw_out = vw_out.append({'id':str(row['id']),
  			'classification':str(s.sentiment(str(row['text']))[0])},
  			ignore_index = True)
    except KeyboardInterrupt:
      print('Writing to file...output/vw_classified_' + input_lang + '.csv')
      vw_out.to_csv('output/vw_classified_' + input_lang + '.csv')
      sys.exit()

  print('Writing to file...output/vw_classified_' + input_lang + '.csv')
  vw_out.to_csv('output/vw_classified_' + input_lang + '.csv')
    def on_data(self, data):
        all_data = json.loads(data)
        
        tweet = ascii(all_data["text"])
        sentiment_value, confidence = s.sentiment(tweet)
        print((tweet, sentiment_value, confidence))

        if confidence*100 >=80:
            output = open("your output file goes here","a")
            output.write(sentiment_value)
            output.write('\n')
            output.close()
        time.sleep(0.3)
        return True
コード例 #7
0
ファイル: Main.py プロジェクト: rajakamraj/Sentiment-Analyzer
 def printh(self):
     try:
         selectedRadio=''
         if(self.radioNaiveBayes.isChecked()):
             selectedRadio='naivebayes'
         elif(self.radioMNB.isChecked()):
             selectedRadio='mnb'
         elif(self.radioBernoulliNB.isChecked()):
             selectedRadio='bernoullinb'
         elif(self.radioLogisticRegression.isChecked()):
             selectedRadio='logisticregression'
         elif(self.radioSGDClassifier.isChecked()):
             selectedRadio='sgd'
         elif(self.radioSVC.isChecked()):
             selectedRadio='svc'
         elif(self.radioLinearSVC.isChecked()):
             selectedRadio='linearsvc'
         elif(self.radioAlchemyAPI.isChecked()):
             selectedRadio='alchemy'
         elif(self.radioVoted.isChecked()):
             selectedRadio='ensemble'
             
         if(selectedRadio is ''):
             QtGui.QMessageBox.warning(self, 'Error!', 'You have not selected any classifiers')
             return   
         
         i=0;
         print(len(bookName))
         self.dbu = db.DatabaseUtility('UsernamePassword_DB', 'reviewDetails')
         self.dbu.tableName='reviewDetails'
         for i in range(len(bookName)):
             print(bookName.__getitem__(i))
             if(selectedRadio in ('alchemy')):
                 response = alchemyapi.sentiment("text", reviewerReview.__getitem__(i))
                 review_type =response["docSentiment"]["type"]
                 if(review_type in  ('positive','negative')):
                     sentimentValue= review_type
                 else:
                     sentimentValue='positive'
             else:
                 sentimentValue=s.sentiment(reviewerReview.__getitem__(i))
             if(not sentimentValue):
                 sentimentValue='positive'
             self.dbu.AddEntryToTableReview(bookName.__getitem__(i),reviewerName.__getitem__(i),reviewerReview.__getitem__(i),sentimentValue.__str__())
             i=i+1
     except IOError as exc:
         if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it.
             raise  
     MainWindow.resultWindow(self.parent())
コード例 #8
0
    def on_data(self, data):
        try:
            all_data = json.loads(data)

            tweet = all_data["text"].lower()
            count = all_data["retweet_count"] + all_data["favorite_count"]
            sentiment_value, confidence = s.sentiment(tweet)
            print(tweet, sentiment_value, confidence)

            if confidence * 100 >= 80 and ("ndp" in tweet or "mulcair" in tweet):
                output = open("twitter-NDP.txt", "a")
                if count == 0:
                    output.write(sentiment_value)
                    output.write("\n")
                else:
                    for x in xrange(count):
                        output.write(sentiment_value)
                        output.write("\n")
                output.close()

            if confidence * 100 >= 80 and ("liberal" in tweet or "trudeau" in tweet):
                output = open("twitter-liberal.txt", "a")
                if count == 0:
                    output.write(sentiment_value)
                    output.write("\n")
                else:
                    for x in xrange(count):
                        output.write(sentiment_value)
                        output.write("\n")
                output.close()

            if confidence * 100 >= 80 and ("conservative" in tweet or "harper" in tweet):
                output = open("twitter-conservative.txt", "a")
                if count == 0:
                    output.write(sentiment_value)
                    output.write("\n")
                else:
                    for x in xrange(count):
                        output.write(sentiment_value)
                        output.write("\n")
                output.close()

            return True

        except:
            return True
コード例 #9
0
ファイル: rate_opinion.py プロジェクト: atul46/the-code
def get_set_review_rate():
    #for data in db[config.REVIEW_COLLECTION].find({'_id': 'com.supercell.boombeach'}, {'latest_reviews':1, 'crawling_date': 1}):
    for data in db.snapv2_0.find({},{'latest_reviews':1, 'crawling_date': 1}):
        if len(data['latest_reviews']) < 40:
            continue
        data_dict = {}
        data_dict['_id'] = data['_id']
        data_dict['review_date'] = [ data['crawling_date'][-1] ]

        app_rev = data['latest_reviews']
        p_score = n_score  = 0
        p_rev = n_rev = ''

        for rev in app_rev:
            result = rate.sentiment(rev)[0]
            if result == 'pos':
                p_score += 1
                p_rev += rev
            elif result == 'neu':
                pass
            else:
                n_score += 1
                n_rev += rev

        #calculate the score
        data_dict['p_percent'] = p_score / ( p_score + n_score ) 
        data_dict['n_percent'] = n_score / ( p_score + n_score )
        #counter with most common 20 words
        data_dict['positive_cloud'] = Counter([w for w in p_rev.lower().split() if w not in stop_words and len(w) > 2]).most_common(20)
        data_dict['negative_cloud'] = Counter([w for w in n_rev.lower().split() if w not in stop_words and len(w) > 2]).most_common(20)

        try:
            db[config.RATED_COLLECTION].insert(data_dict)
        except pymongo.errors.DuplicateKeyError as e:
            db[config.RATED_COLLECTION].update(
                                                {'_id': data_dict['_id']},
                                                {
                                                '$push': {
                                                            'n_percent': data_dict['n_percent'][0], 
                                                            'p_percent': data_dict['p_percent'][0],
                                                            'date' : data_dict['review_date'][0]},
                                                '$set': {
                                                            'negative_cloud': data_dict['negative_cloud'], 
                                                            'positive_cloud': data_dict['positive_cloud']}
                                                })
コード例 #10
0
ファイル: 20_Twitter_Sentiment.py プロジェクト: altock/dev
    def on_data(self,data):
        try:
            all_data = json.loads(data)
            tweet = all_data['text']


            sentiment_value, confidence = s.sentiment(tweet)
            print(tweet, sentiment_value, confidence*100)
            if confidence*100 >= 80:
                output = open('twitter-out.txt', 'a')
                output.write(sentiment_value)
                output.write('\n')
                output.close()
            time.sleep(0.25)
            return True
        except BaseException:
            print('failed ondata')
            time.sleep(5)
コード例 #11
0
	def on_data(self,data):	
		all_data = json.loads(data)
		tweet = all_data["text"]
		tweet = re.sub("@[\S]+","",tweet)
 		tweet = re.sub("((www.\.[^\s]+)|(http?://[^\s]+))","",tweet)
		tweet = tweet.lower()
		if ("makes" in tweet)|("i'm" in tweet)|("feel" in tweet)|("i am" in tweet):
 
			sentiment_value, confidence = s.sentiment(tweet)
			print(tweet, sentiment_value, confidence)

			if confidence*100 >= 80:
				output = open("twitter-out.txt","w")
				output.write(sentiment_value)
				output.write('\n')
				output.close()
	
		return True
コード例 #12
0
    def on_data(self, data):
        try:
            all_data = json.loads(data)
            tweet = all_data["text"]
            createdat = all_data["created_at"]
            ff=open("output_singleteam/alltweet.txt",'a')
            sentiment_value, confidence = s.sentiment(tweet)
            ff.write(str(createdat)+" "+str(tweet)+" "+ str(sentiment_value)+" "+str( confidence)+"\n")
            ff.close()
            if confidence*100 >= 70:
                        output = open("output_singleteam/twitter-out.txt","a")
                        output.write(sentiment_value)
                        output.write('\n')
                        output.close()

            return True
        except:
            return True
コード例 #13
0
 def on_data(self, data):
     try:
         all_data = json.loads(data)     #Use json to apply on tweet.
         tweet = all_data["text"]
         sentiment_value,confidence = s.sentiment(tweet)
         print(tweet,sentiment_value,confidence)
         if confidence*100 >= 80:    #So more than 0.8 confidence value counted as accurate result for sentniment
             output = open("Barbershop.txt","a")  #Save tweets with sentiment and confidence value
             output.write(tweet)
             output.write("      ")
             output.write(sentiment_value)
             output.write(":::::")
             output.write(confidence)
             output.write("\n")
             output.close()
         return True
     except BaseException as e:
         print (e)
         time.sleep(5)
コード例 #14
0
    def on_data(self, data):
        try:
            all_data = json.loads(data)
            tweet = all_data["text"].lower()
            createdat = all_data["created_at"]
            ff=open("output_twoteam/alltweet.txt",'a')
            sentiment_value, confidence = s.sentiment(tweet)
            ff.write(json.dumps(all_data)+" "+ str(sentiment_value)+" "+str(confidence)+"\n")
            ff.close()
            if confidence*100 >= 0:
                if re.search("team1",tweet) :       ## NOTE-- change team1 by your team1 name
                        output = open("output_twoteam/team1res.txt","a")
                        output.write(sentiment_value)
                        output.write('\n')
                        output.close()
                if re.search("team2",tweet) :       ## NOTE-- change team2 by your team2 name
                        output = open("output_twoteam/team2res.txt","a")
                        output.write(sentiment_value)
                        output.write('\n')
                        output.close()        

            return True
        except:
            return True
コード例 #15
0
    def submitLoad(self):
        foundSymbol = 0
        for a in loadTr :
            for b in word_tokenize(a):
                listWord.append(b)
            for b in sent_tokenize(a):
                sentence.append(b)
            


        for a in listWord:
            stemmedList.append(ps.stem(a))


        for a in stemmedList : 
            for b in notCount :
                if a==b:
                    foundSymbol = 1
            if foundSymbol !=1:      
                filteredList.append(a)

                foundSymbol = 0
            foundSymbol = 0

        for a in filteredList :
            lower.append(a.lower())
            wordCollect.append(a.lower())
        
        a = ' '.join(listWord)
        b = ' '

  
        savedWord = []
        wordFreq = []
        

        c = Counter(lower)


        del listWord[:]
        del newListWord[:]                   
        del stemmedList[:]
        del lower[:]
        del uniToStr[:]
        del savedWord[:]
        del wordFreq[:]
        artCount = 0
        comScCount = 0
        for a in sentence :
            if (s.sentiment(a))=="art" : ## check type for each sentence
                artCount = artCount +1
            else :
                comScCount = comScCount +1

        allType = artCount + comScCount  ## calculate all word numbers
        artPercent = float((float(artCount)/float(allType)))*100
        comScPercent = float((float(comScCount)/float(allType)))*100
        
        if artPercent > comScPercent : 
            typeText = "ART"        ## if number of art sentence > com then it's ART
            for word in sentence :
                artWord.append(word)
            for a in filteredList :
                PArt.append(a.lower())
        else :
            typeText = "COMPUTER SCIENCE" ## if not its COM
            for word in sentence :
                comScWord.append(word)
            for a in filteredList :
                PComSc.append(a.lower())
    
        
        
     
        del sentence[:]
        del filteredList[:]
コード例 #16
0
    def submitLink(self):   ### PRESS SUBMIT
    
            
          
            for link in getLink:
                        r = requests.get(link)
                        r.content
                        soup = BeautifulSoup(r.content,"lxml")
                        g_data =soup.find_all("p")
                        foundSymbol = 0
                        for a in loadTr :
                            for b in word_tokenize(a.text):
                                listWord.append(b)
                            for b in sent_tokenize(a.text):
                                sentence.append(b)
                            
                        for a in g_data :
                        
                            for b in word_tokenize(a.text):
                                listWord.append(b)
                            for b in sent_tokenize(a.text):
                                sentence.append(b)


                        for a in listWord:
                            stemmedList.append(ps.stem(a))


                        for a in stemmedList : 
                            for b in notCount :
                                if a==b:
                                    foundSymbol = 1
                            if foundSymbol !=1:      
                                filteredList.append(a)

                                foundSymbol = 0
                            foundSymbol = 0

                        for a in filteredList :
                            lower.append(a.lower())
                            wordCollect.append(a.lower())
                        
                        a = ' '.join(listWord)
                        b = ' '

                  
                        savedWord = []
                        wordFreq = []
                        

                        c = Counter(lower)


                        del listWord[:]
                        del newListWord[:]                   
                        del stemmedList[:]
                        del lower[:]
                        del uniToStr[:]
                        del savedWord[:]
                        del wordFreq[:]
                        artCount = 0
                        comScCount = 0
                        for a in sentence :
                            if (s.sentiment(a))=="art" : ## check type for each sentence
                                artCount = artCount +1
                            else :
                                comScCount = comScCount +1

                        allType = artCount + comScCount  ## calculate all word numbers
                        artPercent = float((float(artCount)/float(allType)))*100
                        comScPercent = float((float(comScCount)/float(allType)))*100
                        
                        if artPercent > comScPercent : 
                            typeText = "ART"        ## if number of art sentence > com then it's ART
                            for word in sentence :
                                artWord.append(word)
                            for a in filteredList :
                                PArt.append(a.lower())
                        else :
                            typeText = "COMPUTER SCIENCE" ## if not its COM
                            for word in sentence :
                                comScWord.append(word)
                            for a in filteredList :
                                PComSc.append(a.lower())
                        typeList.append((link,typeText))
                        
                        
                     
                        del sentence[:]
                        del filteredList[:]
            
          
            
            save_typeList = open("data_input/typelist.pickle","wb")
            pickle.dump(typeList, save_typeList) ## save link and type to pickle for future usage
            save_typeList.close()
コード例 #17
0
print '1 starting'
import sentiment_mod as s

#using a sentiment module 
print 'starting'
print(s.sentiment("This movie was awesome! The acting really was wonderful, and the plot was epic!"))
print(s.sentiment("This movie was utter gargbage. There was absolutely nothing worse seeing in the movie. I didn't understand the point in going to it."))
コード例 #18
0
#!/usr/bin/python3.4
# -*- coding: utf-8 -*-
# classify text

import sentiment_mod as s

print(s.sentiment("This movie was awesome! The acting was great, plot was wonderful, and there were pythons...so yea!"))
print(s.sentiment("This movie was utter junk. There were absolutely 0 pythons. I don't see what the point was at all. Horrible movie, 0/10"))
print(s.sentiment("very bad movie"))
print(s.sentiment("very good"))
print(s.sentiment("this is a very enjoyable movie. you will leave it feeling good, and maybe thinking a bit as well. think dolphin tale. wish they had the ski jump sceens in imax"))
print(s.sentiment("Inspiring story. A bit hollywood'ish. Moves right along with good acting. Our entire family enjoyed it. "))

コード例 #19
0
import sentiment_mod as s
import tweetProcess as ts

testing1="It is very sad that nike hiked prices of jogging shoes."
testing2="#Nike got the amazing range of soccer shoes.#FCBarca"
print(testing1,s.sentiment(testing1))
print(testing2,s.sentiment(testing2))
コード例 #20
0
def post_user():
    text = request.form['username']
    return ''.join(s.sentiment(text))
コード例 #21
0
import sentiment_mod as s

print(s.sentiment("faslkf lsafdj jsas"))
#print(s.sentiment("This movie was awesome! The acting was great, plot was wonderful, and there were pythons...so yea!"))
#print(s.sentiment("This movie was utter junk. There were absolutely 0 pythons. I don't see what the point was at all. Horrible movie, 0/10"))
コード例 #22
0
import sentiment_mod as s

print(s.sentiment("This movie was awesome, the acting was great, the plot was wonderful and there were pythons... so yeah!"))
print(s.sentiment("This movie was utter junk, there were absolutely zero pythons. I don't see what the point was at all. Horrible movie 0/10"))
コード例 #23
0
ファイル: sentiment_test.py プロジェクト: amrrs/DSstuff
import sentiment_mod as s

print(s.sentiment("This was one epic adventure they call a film! It had a thrilling plot and impressive star cast. Will watch it again on monday."))
print(s.sentiment("Horrible movie. Watching it is like being punished by cinema"))
コード例 #24
0
import sentiment_mod as s

print(
    s.sentiment(
        "This movie was awesome! The acting was great, plot was wonderful, and there story was good"
    ))
print(
    s.sentiment(
        "This movie was terrible. There were absolutely 0 storyline. I don't see what the point was at all. Horrible movie, 0/10"
    ))
print(
    s.sentiment(
        "The movie was great! I loved all of the actors! Ironman is always very cool to watch. But I didn't like the action."
    ))

print(s.sentiment("This movie is as awesome as the Emoji movie."))
コード例 #25
0
import sentiment_mod as s

print(s.sentiment("This movie was awesome! The acting was great, plot was wonderful, and there were pythons...so yea!"))
print(s.sentiment("This movie was utter junk. There were absolutely 0 pythons. I don't see what the point was at all. Horrible movie, 0/10"))
print(s.sentiment("Great CD: My lovely Pat has one of the GREAT voices of her generation. I have listened to this CD for YEARS and I still LOVE IT. When I'm in a good mood it makes me feel better. A bad mood just evaporates like sugar in the rain. This CD just oozes LIFE. Vocals are jusat STUUNNING and lyrics just kill. One of life's hidden gems. This is a desert isle CD in my book. Why she never made it big is just beyond me. Everytime I play this, no matter black, white, young, old, male, female EVERYBODY says one thing \"Who was that singing ?"))
print(s.sentiment("Batteries died within a year ...: I bought this charger in Jul 2003 and it worked OK for a while. The design is nice and convenient. However, after about a year, the batteries would not hold a charge. Might as well just get alkaline disposables, or look elsewhere for a charger that comes with batteries that have better staying power."))
コード例 #26
0
import sentiment_mod as s

# In[3]:

count = 0
with open('part-00000-a2063ab0-7b44-489f-a5d5-1f3ef8cc9dd5-c000.csv',
          encoding="utf8") as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        if count <= 500:
            count = count + 1
            # print(count)
            row1 = str(row)
            #  row = [entry.decode("utf8") for entry in row]
            sentiment_value, confidence = s.sentiment(row1)
            print(sentiment_value)

# In[4]:

if confidence * 100 >= 80:
    output = open("twitter-out.txt", "a")
    output.write(sentiment_value)
    output.write('\n')
    output.close()

# In[5]:

style.use("ggplot")

fig = plt.figure()
コード例 #27
0
ファイル: test.py プロジェクト: KalyanTarun/Projects
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 19 20:56:16 2018

@author: Tarun
"""

import sentiment_mod as s

print(
    s.sentiment(
        "This movie was fabulous.work is top notch.It is a treat to watch and worth watching "
    ))
print(
    s.sentiment(
        "This movie was utter junk. There were absolutely 0 pythons. I don't see what the point was at all. Horrible movie"
    ))
    new_article.parse()
    try:
        cursor.execute(
            "INSERT IGNORE INTO sentinews(TITLE,NEWS,IMAGE,SENTI,CODE) VALUES(%s,%s,%s,%s,%s)",
            (new_article.title, new_article.text, new_article.top_image, 0,
             "a"))
        conn.commit()
    except Exception as e:
        print(e)

cursor.execute('SELECT * FROM sentinews')

result_set = []

for p in cursor.fetchall():
    result_set.append(s.sentiment(p[2]))

for i in list(range(len(result_set))):
    if result_set[i][0] == 'pos':
        try:
            cursor.execute(
                "UPDATE sentinews SET CODE='pos',SENTI={} WHERE ID={}".format(
                    result_set[i][1], i + 1))
            conn.commit()
        except Exception as e:
            print(e)

    elif result_set[i][0] == 'neg':
        try:
            cursor.execute(
                "UPDATE sentinews SET CODE='neg',SENTI={} WHERE ID={}".format(
コード例 #29
0
import sentiment_mod as s
import unittest 
a =(s.sentiment("computer science complete "))
print(s.sentiment("the art  rock is destined to be the 21st century's new " 'conan' " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal . l"))
print(s.sentiment("This art movie was awesome! The new acting was great, plot was so wonderful, and there were big pythons...so yea!"))
print(s.sentiment("This movie was utter junk. There were absolutely bad. I don't see what the point was at all. Horrible movie, 0/10 "))
print(s.sentiment("i love microcomputer assymbly "))
print(s.sentiment("The term hardware covers all of those parts of a computer that are tangible objects. Circuits, displays, power supplies, cables, keyboards, printers and mice are all hardware."))
print(s.sentiment("complete computer assymbly "))
print(s.sentiment("computer science complete "))
print(s.sentiment("Drawing is a means of making an image, using any of a wide variety of tools and techniques. "))
print a

s.showWord()



コード例 #30
0
ファイル: testCase.py プロジェクト: Centpledge/BUILDING-2
import sentiment_mod as s

class testCase():
    def testMod(self,outResult,expectedResult1,expectedResult2 = None):
        if outResult == expectedResult1 :
            print "OK"
            print outResult
            print " "
            
        else :
            print "ERROR"
            print outResult
            print " "
s.showWord()
testCase().testMod(s.sentiment("first object "),"art") #OK
testCase().testMod(s.sentiment("art"),"art")# OK
testCase().testMod(s.sentiment("mechanical "),"comSc") # OK
testCase().testMod(s.sentiment("aesthetic social public   "),"art")#OK
testCase().testMod(s.sentiment("integrated  less useful   "),"comSc") #OK
testCase().testMod(s.sentiment("logical single short  "),"comSc") #OK
testCase().testMod(s.sentiment("traditional able "),"art")#OK
testCase().testMod(s.sentiment("traditional able "),"comSc")#ERROR 
testCase().testMod(s.sentiment("great  further "),"art")#OK
testCase().testMod(s.sentiment("great  further "),"comSc")#ERROR
testCase().testMod(s.sentiment(" notable material same required  "),"comSc") # 3.6 3.6 3.8 3.8
testCase().testMod(s.sentiment("object able "),"comSc")# 3.3 3.6 ERROR
testCase().testMod(s.sentiment("object same "),"comSc") # 3.3 3.8 ERROR
testCase().testMod(s.sentiment("object logical "),"comSc") #3.3 4.8  OK
testCase().testMod(s.sentiment("object step "),"comSc") #3.3 4.5 OK
testCase().testMod(s.sentiment("traditional step "),"comSc") # 3.6 4.5 OK
testCase().testMod(s.sentiment("special popular object "),"comSc") # 3.2 3.2 3.3 OK
コード例 #31
0
import sentiment_mod as s

print(s.sentiment("This is a great movie"))
print(s.sentiment("This movie was utter junk"))
コード例 #32
0
def process_sentiment(tweet_doc):
    tweet = tweet_doc['text']
    tweet_doc['SENTIMENT'] = sentiment.sentiment(tweet)
    return tweet_doc
コード例 #33
0
# print review_file.read()

# x = ['ketaki' , 'harsh' , 'gaikwad']
# print '{0:10d}'.format(x)
# with open("review.txt", 'r') as fin:
#     print fin.read()

# lst = raw_input('Your Name : ')
# print "Your name is %s" % lst

# myList  = ["The food was worst, the service was bad. But the ambience was amazing.", "I am awesome.", "Do no go gentle into that good night.","It is such a powerful world.","never give up. you can win.","I love it.","Decent battery.","Screen size is too big","Not enough memory."]

# for l in myList:
# 	print(s.sentiment(l))

# Writing result of sentiment to a text file
# text_file = open("OutputReview.txt","w");
# text_file.write(s.sentiment("The food was bad, the service was great. The ambience was amazing."));
# text_file.write(s.sentiment("The food was bad, the service was great. The ambience was amazing."));
# text_file.write(s.sentiment("I am awesome."));
# text_file.write(s.sentiment("Do no go gentle into that good night."));

print(s.sentiment("I am very scared."))
print(s.sentiment("It is a bad phone."))
print(s.sentiment("The acting was unpleasent."))
print(s.sentiment("I love the battery on the phone."))
print(s.sentiment("I am happy."))
print(s.sentiment("This is bad."))
x = raw_input()
print(s.sentiment(x))
コード例 #34
0
from tweepy import Stream
コード例 #35
0
import sentiment_mod as s

##print(s.sentiment(r"This movie was awesome, acting was great, plot was wonderful and there\
## were pythons."))
##print(s.sentiment(r"This movie was utter junk. There were absolutely \
##0 pythons. I don't see what the point was at all. Horrible movie 0/10"))

#pos
data = open('WonderStruck.txt', 'r', encoding="utf8").read()
data = data.replace('Advertisement', '')
print(s.sentiment(data))

data = open('BadMomsChristMas.txt', 'r', encoding="utf8").read()
data = data.replace('Advertisement', '')
print(s.sentiment(data))

data = open('SavingChristmas.txt', 'r', encoding="utf8").read()
data = data.replace('Advertisement', '')
print(s.sentiment(data))

#pos
data = open('BalladOfNarayama.txt', 'r', encoding="utf8").read()
data = data.replace('Advertisement', '')
print(s.sentiment(data))

#medium neg>pos
data = open('BladeOfImmortal.txt', 'r', encoding="utf8").read()
data = data.replace('Advertisement', '')
print(s.sentiment(data))
コード例 #36
0
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 15:07:10 2019

@author: Shyam Parmar
"""

import sentiment_mod as s

print(
    s.sentiment(
        "This movie was awesome! The acting was great, plot was wonderful, and there were pythons...so yea!"
    ))
print(
    s.sentiment(
        "This movie was utter junk. There were absolutely 0 pythons. I don't see what the point was at all. Horrible movie, 0/10"
    ))
コード例 #37
0
product.send_keys(Keys.RETURN)
driver.find_element_by_class_name("_2cLu-l").click()
#print search.text

#time.sleep(100)
driver.save_screenshot('testing1.png')

reviews = driver.find_elements_by_class_name("qwjRop")
import sentiment_mod as s
pos = 0
neg = 0

for review in reviews:
    if (review.text != ''):
        #print(review.text)
        if (s.sentiment(review.text) == 'pos'):
            #print("positive ")
            pos = pos + 1
        else:
            #print("negative")
            neg = neg + 1

if (pos > neg):
    rating = "The product review is overall positive"
    cl = 'green'

elif (neg > pos):
    rating = "The product review is overall negative"
    cl = 'red'

else:
コード例 #38
0
                                  MNB_classifier,
                                  BernoulliNB_classifier,
                                  LogisticRegression_classifier)

print("voted_classifier accuracy percent:", (nltk.classify.accuracy(voted_classifier, testing_set))*100)


def sentiment(text):
    feats = find_features(text)
    return voted_classifier.classify(feats),voted_classifier.confidence(feats)


###################################################################################
import sentiment_mod as s

print(s.sentiment("This movie was awesome! The acting was great, plot was wonderful, and there were pythons...so yea!"))
print(s.sentiment("This movie was utter junk. There were absolutely 0 pythons. I don't see what the point was at all. Horrible movie, 0/10"))
###################################################################################

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json

#consumer key, consumer secret, access token, access secret.
ckey="584yaMOX3ns6hf0LTyHSag"
csecret="vat4IszkzgZPgPRjaANehWuYp4QpY3wHqCVzY4yYU"
atoken="1533644486-ZpkQGsqTzY4Vnzx9gdY82TynxkSSv7xMs8xW7Vx"
asecret="eivN11Z8vQrDKDpkKQ13g6eg2hSeRpJB8Tq46tvs0M"

import sentiment_mod as s
print(
    s.sentiment(
        "the movie was awesome, the acting was great plot was wonderful and it is excellent"
    ))
print(
    s.sentiment(
        "his health condition was very bad which eventually lead to his death")
)
コード例 #40
0
import sentiment_mod as s
import tweet_preprocessor as prep

# print(s.sentiment(prep.processTweet("I haaaaate all minions!! I better kill time watching www.youtube.com")))
# print(s.sentiment(prep.processTweet("I love minions")))
print(s.sentiment(prep.processTweet("Me encantan los minions")))
コード例 #41
0
import sentiment_mod as s

print(
    s.sentiment(
        "This movie was awesome! The acting was great, plot was wonderful"))
print(
    s.sentiment(
        "This movie was junk. I don't see what the point was at all. Horrible movie, 0/10"
    ))