本文整理汇总了Python中textblob.TextBlob.translate方法的典型用法代码示例。如果您正苦于以下问题:Python TextBlob.translate方法的具体用法?Python TextBlob.translate怎么用?Python TextBlob.translate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类textblob.TextBlob
的用法示例。
在下文中一共展示了TextBlob.translate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: matchRhyme
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def matchRhyme(word1,word2):
#str1 = "tekst"
#word1+="टेक्स्ट"
str1 = ""
str2 = ""
word1+= "टेक्स्ट"
word2+= "टेक्स्ट"
str1 += " " + word1
str2 += " " + word2
hindi_blob1 = TextBlob(str1)
hindi_blob2 = TextBlob(str2)
transliteratedtxt1 = hindi_blob1.translate(from_lang="hi", to='en')
transliteratedtxt1=transliteratedtxt1.substring[:-5]
transliteratedtxt2 = hindi_blob2.translate(from_lang="hi", to='en')
transliteratedtxt2= transliteratedtxt2.substring[:-5]
word1Index= len(transliteratedtxt1)
word2Index= len(transliteratedtxt2)
##Matcing last charater if they are same!!
if (transliteratedtxt1[word1Index-1] == transliteratedtxt2[word2Index-1]):
#rhymeMeter=3;
##Matching if second Last character is any of the Matras!!
if ( ((transliteratedtxt1[word1Index-2]=='a') and (transliteratedtxt2[word2Index-2]=='a')) or ((transliteratedtxt1[word1Index-2]=='e') and (transliteratedtxt2[word2Index-2]=='e'))or ((transliteratedtxt1[word1Index-2]=='o') and (transliteratedtxt2[word2Index-2]=='o')) or ((transliteratedtxt1[word1Index-2]=='i') and (transliteratedtxt2[word2Index-2]=='i')) or ((transliteratedtxt1[word1Index-2]=='u') and (transliteratedtxt2[word2Index-2]=='u')) ):
rhymeMeter=5
else:
if(transliteratedtxt1[word1Index-2]!=transliteratedtxt1[word1Index-2]):
rhymeMeter=4
return rhymeMeter
示例2: scrape
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def scrape(self,links=[],ads=True,translator=False):
responses = []
values = {}
data = []
if ads:
for link in links:
r = requests.get(link)
responses.append(r)
else:
for link in links:
r = requests.get(link)
text = unidecode(r.text)
html = lxml.html.fromstring(text)
links = html.xpath("//div[@class='cat']/a/@href")
for link in links:
if len(self.base_urls) > 1 or len(self.base_urls[0]) > 3:
time.sleep(random.randint(5,27))
try:
responses.append(requests.get(link))
print link
except requests.exceptions.ConnectionError:
print "hitting connection error"
continue
for r in responses:
text = r.text
html = lxml.html.fromstring(text)
values["title"] = html.xpath("//div[@id='postingTitle']/a/h1")[0].text_content()
values["link"] = unidecode(r.url)
values["new_keywords"] = []
try:
values["images"] = html.xpath("//img/@src")
except IndexError:
values["images"] = "weird index error"
pre_decode_text = html.xpath("//div[@class='postingBody']")[0].text_content().replace("\n","").replace("\r","")
values["text_body"] = pre_decode_text
try:
values["posted_at"] = html.xpath("//div[class='adInfo']")[0].text_content().replace("\n"," ").replace("\r","")
except IndexError:
values["posted_at"] = "not given"
values["scraped_at"] = str(datetime.datetime.now())
body_blob = TextBlob(values["text_body"])
title_blob = TextBlob(values["title"])
values["language"] = body_blob.detect_language() #requires the internet - makes use of google translate api
values["polarity"] = body_blob.polarity
values["subjectivity"] = body_blob.sentiment[1]
if values["language"] != "en" and not translator:
values["translated_body"] = body_blob.translate(from_lang="es")
values["translated_title"] = title_blob.translate(from_lang="es")
else:
values["translated_body"] = "none"
values["translated_title"] = "none"
text_body = values["text_body"]
title = values["title"]
values["phone_numbers"] = self.phone_number_parse(values)
data.append(values)
return data
示例3: sentiment
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def sentiment():
doob = "Great Movie!"
blob = TextBlob(doob)
for sentence in blob.sentences:
print(sentence.sentiment)
print blob.translate(to="cn")
示例4: to_english
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def to_english(message, original_language=None):
blob = TextBlob(text)
if original_language is not None:
return blob.translate(from_lang=original_language, to="en")
else:
return blob.translate(to="en")
示例5: getSentimentScore
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def getSentimentScore (text):
blob = TextBlob(text)
blob.tags
blob.noun_phrases
try:
blob.translate(to="en")
print blob
except:
print"No translation needed for English text"
sentimentScore = blob.sentiment.polarity
return sentimentScore
示例6: keywordResultsCount
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def keywordResultsCount(self, inputs):
self.inputs = inputs['general']
params = self.mapParameters(inputs)
print 'ushmm'
print params
try:
if 'German'in params:
g = params['Solr__Query']
z1 = str(g)
blob = TextBlob(z1)
params['Solr__Query']=str(blob.translate(to="de"))
print params
self.result_search_term = params['Solr__Query']
print self.result_search_term
if 'French' in params:
g = params['Solr__Query']
z1 = str(g)
blob = TextBlob(z1)
params['Solr__Query']=str(blob.translate(to="fr"))
print params
self.result_search_term = params['Solr__Query']
print self.result_search_term
except:
pass
'''
query = inputs['general'].split(' ')
x=len(query)
'''
url = "http://www.errproject.org/jeudepaume/card_advanced_search.php"
r = requests.get(url, params=params)
html = r.text
soup = BeautifulSoup(html, "lxml")
results = soup.find_all("tr", class_="results")
count = results.__len__()
'''
if (x>1):
self.result_search_term = query[1]
else:
self.result_search_term = query[0]
'''
#self.result_search_term = 'none'
self.results_url = r.url
self.results_count = count
return self
示例7: split_sentence_based_on_verbs
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def split_sentence_based_on_verbs(reviewText):
review_spacy = nlp(reviewText)
review_textblob = TextBlob(reviewText)
if not review_textblob.detect_language() == 'en':
review_textblob = review_textblob.translate(to='en')
review_spacy = nlp(review_textblob.string)
else:
contains_romanian_words = 0
for word in review_textblob.words:
word_textblob = TextBlob(word)
if len(word_textblob.string) >= 3 and word_textblob.detect_language() == 'ro':
contains_romanian_words = 1
break
if contains_romanian_words == 1:
new_reviewText = ''
for word in review_spacy:
word_textblob = TextBlob(word.orth_)
if not word.is_title and len(word_textblob.string) >= 3:
if word_textblob.detect_language() != 'ro':
new_reviewText = new_reviewText + ' ' + word_textblob.string
else:
new_word = word_textblob.translate(to='en')
new_reviewText = new_reviewText + ' ' + new_word.string
else :
new_reviewText = new_reviewText + ' ' + word_textblob.string
# only_english_words = 0
# break
review_textblob = TextBlob(new_reviewText)
review_spacy = nlp(review_textblob.string)
new_sentences = []
verbs_positions = []
for k in range(0, len(review_spacy)):
if review_spacy[k].pos == VERB and review_spacy[k].dep_ == 'ROOT':
verbs_positions.append(k)
start = 0
if len(verbs_positions) > 0:
for p in range(0, len(verbs_positions)):
if p == len(verbs_positions) - 1:
new_sentences.append(review_spacy[start:len(review_spacy)].text)
else:
q = verbs_positions[p] + 1
while q < len(review_spacy):
if review_spacy[q].is_stop and ((review_spacy[q].pos == CONJ and (q < len(review_spacy)-1 and review_spacy[q-1].pos != review_spacy[q+1].pos)) or (review_spacy[q].pos == DET and review_spacy[q].lower_ in ['the', 'this', 'those', 'which', 'other', 'another']) or (review_spacy[q].pos == PUNCT and review_spacy[q] in [',', ';'])):
new_sentences.append(review_spacy[start:q].text)
start = q
break
q += 1
else:
new_sentences.append(reviewText)
return new_sentences
示例8: parse_text_meta_data
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def parse_text_meta_data(self,html,values):
if self.debug: print "Processing textual information - language, polarity, subjectivity.."
body_blob = TextBlob(values["text_body"])
title_blob = TextBlob(values["title"])
values["language"] = body_blob.detect_language() #requires the internet - makes use of google translate api
values["polarity"] = body_blob.polarity
values["subjectivity"] = body_blob.sentiment[1]
if values["language"] != "en" and not translator:
values["translated_body"] = body_blob.translate(from_lang="es")
values["translated_title"] = title_blob.translate(from_lang="es")
else:
values["translated_body"] = "none"
values["translated_title"] = "none"
return values
示例9: translate_msg
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def translate_msg(message):
try:
if (len(message.text) > 3):
b = TextBlob(unicode(message.text))
if (b.detect_language() == "ru"):
tr_text = unicode(b.translate(to="en"))
bot.send_message(message.chat.id, tr_text)
if (b.detect_language() == "en"):
tr_text = unicode(b.translate(to="ru"))
bot.send_message(message.chat.id, tr_text)
except Exception as e:
print (e.message)
bot.send_message(message.chat.id, "Sorry Boss,can't translate :("
" Try another message, please " +
telegram.Emoji.KISSING_FACE)
示例10: _german
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def _german(self, text):
blob = TextBlob(text)
try:
return str(blob.translate(to="en"))
except:
return text
示例11: hi
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def hi(bot, trigger):
lang_codes = ['af', 'ga', 'sq', 'it', 'ar', 'ja', 'az', 'kn', 'eu', 'ko', 'bn', 'la', 'en']
trans = TextBlob('Greetings dear '+trigger.nick+'on the road of life ')
ind = randint(0, 12)
trans = trans.translate(to=lang_codes[ind])
saying = str(trans)
bot.say(saying)
示例12: on_command
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def on_command(self, msg, stdin, stdout, reply):
# pre-process args
# this might mess up if "from" or "to" is left out and
# the message contains "from" or "to"
self._push_character(msg["args"], "from", "-", 1)
self._push_character(msg["args"], "to", "-", 1)
try:
args = self.parser.parse_args(msg["args"][1:])
except (argparse.ArgumentError, SystemExit):
return
# get message from the appropriate place
if args.message:
message = " ".join(args.message)
else:
message = stdin.read().strip()
# translate
from_lang = args.from_language
to_lang = args.to_language
message = TextBlob(message)
try:
translated = message.translate(from_lang=from_lang, to=to_lang)
except:
pass
else:
print(translated, file=stdout)
示例13: _translate_message
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def _translate_message(bot, broadcast_list, context):
if context and "autotranslate" in context:
_autotranslate = context["autotranslate"]
origin_language = _get_room_language(bot, _autotranslate["conv_id"])
for send in broadcast_list:
target_conversation_id = send[0]
response = send[1]
target_language = _get_room_language(bot, target_conversation_id)
if origin_language != target_language:
logger.debug("translating {} to {}".format(origin_language, target_language))
translated = _autotranslate["event_text"]
try:
en_blob = TextBlob(_autotranslate["event_text"])
translated = "{0}".format(en_blob.translate(to=target_language))
#translated = gs.translate(_autotranslate["event_text"], target_language
except Exception:
logger.debug("Translation Api returned string unchanged")
else:
pass
finally:
if _autotranslate["event_text"] != translated:
# mutate the original response by reference
response.extend([
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment('(' + translated + ')')])
示例14: gen_translate
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def gen_translate(msg, fromlang=None, outputlang='en'):
try:
blob = TextBlob(msg)
blob = blob.translate(from_lang=fromlang, to=outputlang)
return str(blob)
except NotTranslated:
return msg
示例15: process_status
# 需要导入模块: from textblob import TextBlob [as 别名]
# 或者: from textblob.TextBlob import translate [as 别名]
def process_status(status, lang):
text = ""
# translate
if lang == 'en':
text = status['text']
else:
blob = TextBlob(status['text'])
try:
text = str(blob.translate())
except textblob.exceptions.NotTranslated:
text = status['text']
# sentiment analysis
sentiment = TextBlob(text).sentiment
return {
"created_at": 1000 * int(time.mktime((status['created_at']).timetuple()))
, "id_str": status['id_str']
, "text": text
, "sentiment": {"polarity": sentiment[0], "subjectivity": sentiment[1]}
, "retweet_count": status['retweet_count']
, "in_reply_to_status_id_str": status['in_reply_to_status_id_str']
, "geo": status['geo']
, "retweeted": status['retweeted']
, "in_reply_to_user_id_str": status['in_reply_to_user_id_str']
}