本文整理汇总了Python中alchemyapi.AlchemyAPI.sentiment方法的典型用法代码示例。如果您正苦于以下问题:Python AlchemyAPI.sentiment方法的具体用法?Python AlchemyAPI.sentiment怎么用?Python AlchemyAPI.sentiment使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类alchemyapi.AlchemyAPI
的用法示例。
在下文中一共展示了AlchemyAPI.sentiment方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: user_list_sentiments
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def user_list_sentiments(request):
"""
This function lists all users
:param request: GET request from front end
:return: list of all users
"""
if request.method == 'GET':
users = []
user = User.objects.all()
# docSentimentscore = 1
for u in user:
messages = []
message = Message.objects.filter(user_send=u.user_name)
for m in message:
messages.append(m.message_text)
text = ",".join(messages)
alchemyapi = AlchemyAPI()
response = alchemyapi.sentiment('text', text)
if response["status"] == "OK":
if response["docSentiment"]["type"] == "neutral":
docSentimentscore = 0
else:
docSentimentscore = response["docSentiment"]["score"]
usr = {'user_name': u.user_name, 'user_sentiment': docSentimentscore}
users.append(usr)
print(json.dumps(users))
return HttpResponse(json.dumps(users), content_type="application/json")
示例2: sentiment_alchemy
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def sentiment_alchemy(url):
alchemyapi = AlchemyAPI()
response = alchemyapi.sentiment('url', url)
response['usage'] = None
if response['status'] == 'OK':
print('## Response Object ##')
print(json.dumps(response, indent=4))
print('')
print('## Author ##')
print('author: ', response.get('author', ''))
print('')
else:
print('Error in author extraction call: ', response['statusInfo'])
response = alchemyapi.keywords('url', url)
del (response['usage'])
if response['status'] == 'OK':
print('## Response Object ##')
print(json.dumps(response, indent=4))
print('')
print('## Keywords ##')
for keyword in response['keywords']:
print('text: ', keyword['text'].encode('utf-8'))
print('relevance: ', keyword['relevance'])
print('sentiment: ', keyword.get('sentiment', {}).get('type', ''))
if 'score' in keyword.get('sentiment', {}):
print('sentiment score: ' + keyword['sentiment']['score'])
print('')
else:
print('Error in keyword extaction call: ', response.get('statusInfo', ''))
示例3: extractSentimentFromUrl
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def extractSentimentFromUrl(self, url):
"""method for extracting the sentiment associated with the url of a document"""
# creating AlchemyAPI object
alchemyapi = AlchemyAPI()
# requesting json response from AlchemyAPI server
response = alchemyapi.sentiment("url", url)
if response["status"] == "OK":
# getting the sentiment type from the response
sentimentType = response["docSentiment"]["type"]
# checking the sentiment type
if sentimentType == "neutral":
sentimentScore = 0
else:
sentimentScore = response["docSentiment"]["score"]
# instantiating sentiment object
self.sentimentFromUrl = AlchemyStructure.Sentiment()
# set the value for sentiment type
self.sentimentFromUrl.setType(sentimentType)
# set the value for sentiment score
self.sentimentFromUrl.setScore(sentimentScore)
else:
print("Error in sentiment analysis call: ", response["statusInfo"])
示例4: run_sentiment_analysis
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def run_sentiment_analysis(tweets, text_key):
def print_error(response):
# This should be replaced with better logging
print('Error with AlchemyAPI response:')
print(sentiment, '\n')
alchemyapi = AlchemyAPI()
results = []
for item in tweets:
if text_key not in item:
# Assume it's a bad tweet and continue
print(text_key, 'not found in tweet')
continue
sentiment = alchemyapi.sentiment('text', item['words'])
try:
if sentiment['status'].lower() == 'error':
# Unrecognized language, emoji only, etc...
print_error(sentiment)
# Make a deep copy (since it's a nested dictionary)
new_item = copy.deepcopy(item)
sentiment_type = sentiment['docSentiment']['type']
new_item['sentiment_type'] = sentiment_type
if sentiment_type == 'neutral':
new_item['sentiment_score'] = 0
else:
new_item['sentiment_score'] = sentiment['docSentiment']['score']
results.append(new_item)
except Exception as ex:
print(type(ex).__name__)
print_error(sentiment)
return results
示例5: function
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def function():
string = sys.stdin.readline()
alchemyapi = AlchemyAPI()
myText = "I'm excited to get started with AlchemyAPI!"
response = alchemyapi.sentiment("text", myText)
string = "Sentiment: " + response["docSentiment"]["type"]
print string
示例6: AnalyzeSentiment
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def AnalyzeSentiment(searchTerm):
analysisAPI = AlchemyAPI()
pos, neg, neu = (0,0,0)
dataCollection = database_connection(searchTerm)
dataDocuments = dataCollection.find()
tweets = []
sentimentByCountry = {}
tweetLocation = ""
for document in dataDocuments:
try:
if document.get("sentiment", None) == None:
analysisResponse = analysisAPI.sentiment("text", document["text"])
documentSentiment = analysisResponse["docSentiment"]["type"]
dataCollection.update_one({"_id":document["_id"]}, {"$set": {"sentiment": analysisResponse["docSentiment"]}})
else:
documentSentiment = document["sentiment"]["type"]
if documentSentiment == "positive":
pos=pos+1
elif documentSentiment == "negative":
neg=neg+1
else:
neu=neu+1
tweets.append(document["text"].strip()+"\n\n***Tweet-Sentiment: "+documentSentiment+"***\n"+"-"*70)
except:
print("Unable to parse a Tweet as the language is not understood\n")
dataCollection.delete_one({'text':document['text']})
return pos,neg,neu,tweets
示例7: performSA
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def performSA(pname, text):
alchemyapi = AlchemyAPI()
response = alchemyapi.sentiment('text', text)
sentiment = response['docSentiment']
if (sentiment['type']=='neutral'):
sentiment['score']='0'
return sentiment
示例8: sentiment
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def sentiment(demo_html):
alchemyapi = AlchemyAPI()
response = alchemyapi.sentiment('html', demo_html)
if response['status'] == 'OK':
if 'score' in response['docSentiment']:
return (response['docSentiment']['score'])
else:
return (0.12)
示例9: sentiment_analysis
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def sentiment_analysis(text):
alchemy_api = AlchemyAPI()
response = alchemy_api.sentiment("text", text)
try:
float(response["docSentiment"]['score'])
return float(response["docSentiment"]['score'])
except ValueError:
return None
示例10: getScore
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def getScore(text):
alchemyapi = AlchemyAPI()
score = -10
response = alchemyapi.sentiment('html', text)
if 'docSentiment' in response:
if 'score' in response['docSentiment']:
score = float(response['docSentiment']['score'])
return score
示例11: get_sentiment_score
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def get_sentiment_score(text):
if len(text) == 0:
return -1000
#print("getting sentiment for "+text)
alchemyapi = AlchemyAPI()
sentiment_object = alchemyapi.sentiment('text', text)
#pprint(sentiment_object)
if sentiment_object["docSentiment"]["type"] == "neutral":
return 0
return sentiment_object["docSentiment"]["score"]
示例12: GetAlchemyAPIObject
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def GetAlchemyAPIObject():
with open("api_key.txt","r") as aFile:
for line in aFile.read().split("\n"):
if line != "":
api = AlchemyAPI(line)
result = api.sentiment("text","test")
if result["status"] != "ERROR":
return api
print "Could not initialize valid, usable AlchemyAPI object. Consider requesting another API key."
exit()
return None
示例13: __init__
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
class SentimentAnalyzer:
def __init__(self):
self.alchemyapi = AlchemyAPI()
def get_sentiment(self, text):
response = self.alchemyapi.sentiment("text", text)
# print response
if response['status'] == 'OK':
return response["docSentiment"]["type"]
else:
# print response['statusInfo']
return 'none'
示例14: getAlcData
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def getAlcData(arrOfObj):
alchemyapi = AlchemyAPI()
#for x in range(0,len(arrOfObj)):
for x in range(0, 100):
asc = unicodedata.normalize('NFKD', arrOfObj[x].text).encode('ascii','ignore')
print x
print asc
arrOfObj[x].responseEntities = alchemyapi.entities('text',asc, { 'sentiment':1 })
arrOfObj[x].responseKeywords = alchemyapi.keywords('text',asc, { 'sentiment':1 })
arrOfObj[x].responseSentiment = alchemyapi.sentiment('text',asc)
示例15: __init__
# 需要导入模块: from alchemyapi import AlchemyAPI [as 别名]
# 或者: from alchemyapi.AlchemyAPI import sentiment [as 别名]
def __init__(self, query, maxTweet, resultType, nowDate, tweetOrGraph):
#authenticate and create instance of twitter search API
self.api = twitter.Api(
consumer_key = 'CVtJtQ4GNybpv0v9JVpQs7TS3',
consumer_secret = 'xE5uyc1fZjSfvdImaotwO79oiq2DWImeIZnVHtXcDCby0APqo4',
access_token_key = '273450148-azU5GtOidHPiE9ejrPuvFE7fGztl4l58kVYg5jEh',
access_token_secret = 'QJf6FORBROH5s7Zr5pxBrJVMZYz1ceq6EMx4LDkphlFYx'
)
#connect to database
self.database = Database()
#pass through arguements
self.query = query
self.maxTweet = maxTweet
self.resultType = resultType
self.nowDate = nowDate
self.tweetOrGraph = tweetOrGraph
#search for tweets and save to self.search
self.search = self.api.GetSearch(term=self.query, lang='en', result_type=resultType, count=self.maxTweet, max_id='', until=self.nowDate)
#for each tweet
for t in self.search:
#create AlchempyAPI object
alchemyapi = AlchemyAPI()
#find sentiment type
response = alchemyapi.sentiment("text", t.text)
sentiment = response["docSentiment"]["type"]
#find sentiment score, 'neutal' returns none, so catch and assign 0
try:
scoreString = response["docSentiment"]["score"]
score = float(scoreString)
except:
score = 0
#if it's for the tweet table
if (tweetOrGraph == "tweet"):
dictionaryToDatabase = {"text" : t.text, "lang" : t.lang, "screen_name" : t.user.screen_name, "name" : t.user.name, "image" :t.user.profile_image_url, "sentiment" : sentiment, "score" : score, "created_at" : t.created_at[:10]}
#populate tweet table
self.database.popTable(dictionaryToDatabase)
#if it's for the graph table
else:
dictionaryToDatabase = {"score" : score, "created_at" : t.created_at[3:10]}
#populate graph table
self.database.popTableGraph(dictionaryToDatabase)