コード例 #1
0
    def get_recent_tweet(post_wechat=False):
        auth_url = 'https://twitter.com/realDonaldTrump'
        headers = {
            "User-Agent":
            "Mozilla/5.0 (Linux; U; Android 8.0.0; zh-cn; LLD-AL00 Build/HONORLLD-AL00) AppleWebKit/537.36 (KHTML, like Gecko) MQQBrowser/7.3 Chrome/37.0.0.0 Mobile Safari/537.36"
        }
        session = requests.Session()

        session.request('GET', auth_url, headers=headers)
        cookie_obj = session.cookies
        cookie_list = list()
        for key, value in requests.utils.dict_from_cookiejar(
                cookie_obj).iteritems():
            cookie_list.append('{}={}'.format(key, value))
        cookie = '; '.join(cookie_list)
        headers.update({
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Host": "twitter.com",
            "Accept-Language": "en-us",
            "Accept-Encoding": "br, gzip, deflate",
            "Referer": "https://twitter.com/realDonaldTrump",
            "Connection": "keep-alive",
            "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15",
            "Cookie": cookie,
            "X-Requested-With": "XMLHttpRequest",
            "X-Previous-Page-Name": "profile",
            "X-Overlay-Request": "true",
            "X-Twitter-Active-User": "******"
        })

        resp = session.get("https://twitter.com/realDonaldTrump",
                           headers=headers).json()["page"]
        ids = re.findall(r'data-tweet-id=\"(\d+)\"', resp)

        for _id in ids:
            if not search(_id):
                tweet = session.get(
                    "https://twitter.com/realDonaldTrump/status/{id}?conversation_id={id}"
                    .format(id=_id),
                    headers=headers).json()
                tweet_time_str = re.findall(
                    r'realDonaldTrump/status/{}\" class=\"tweet-timestamp js-permalink js-nav js-tooltip\" title=\"(.*)\"\s+'
                    r'data-conversation-id'.format(_id), tweet["page"])[0]
                print _id
                title = tweet["title"]
                translation = translate(tweet["title"])
                tweet_time = datetime.datetime.strptime(
                    tweet_time_str, "%H:%M %p - %d %b %Y")
                insert(_id, tweet["title"], translate(tweet["title"]),
                       tweet_time_str)
                msg = {
                    "content": title,
                    "translation": translation,
                    "time": str(tweet_time)
                }
                if post_wechat:
                    send_msg(msg)
                print "###################"
コード例 #2
0
def resolve(lines):
    """
    翻译字符串
    :param lines: 文件内容
    :return:
    """
    # 翻译结果
    trans_result = ""
    # 待翻译字符串
    string = ""
    # 状态为0说明在代码行, 状态为1说明在注释行
    import re
    for line in lines:
        # TODO 改成正则匹配
        # 无论是否需要翻译,将原文添加到结果中
        trans_result += line
        string += line
        # 匹配是否为/*xxxxx*/,匹配注释前面的空白字符
        res = re.findall(r"([\t| ]*/\*[\s\S]*?\*/)", string)
        if len(res) == 1:
            trans_result += translate(res[0])
            string = ""
        # 匹配当前行是否为 //
        # 只匹配当前行貌似会有问题,出现
        # /**
        # //
        # */
        # 将会出现错误,虽然肯定不会有人这么写,但为了严谨些,关闭匹配//
        # else:
        #     line_res = re.findall(r"^[\s]*// .*$", line)
        #     if len(line_res) == 1:
        #         trans_result += trans(line_res[0])
        #         string = ""
    return trans_result
コード例 #3
0
def translate_screenshot(get_new_key):
    screen_array = screen.grab()
    rgb_screen_array = cv2.cvtColor(screen_array, cv2.COLOR_BGR2RGB)
    img = Image.fromarray(rgb_screen_array)
    region = capture.select_from_image(img)
    if region != None:
        width = region[2] - region[0]
        height = region[3] - region[1]
        rect_area = width * height
        half_rect_area = rect_area // 2
        img = crop(screen_array, region)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        retval, img_1 = cv2.threshold(img, 63, 255, cv2.THRESH_BINARY)
        retval, img_3 = cv2.threshold(img, 191, 255, cv2.THRESH_BINARY)
        count_1 = cv2.countNonZero(img_1)
        reverse_1 = False
        if count_1 < half_rect_area:
            reverse_1 = True
            count_1 = rect_area - count_1
        count_3 = cv2.countNonZero(img_3)
        reverse_3 = False
        if count_3 < half_rect_area:
            reverse_3 = True
            count_3 = rect_area - count_3
        if count_1 < count_3:
            img = img_1
            reverse = reverse_1
        else:
            img = img_3
            reverse = reverse_3
        if reverse:
            img = 255 - img
        text = pytesseract.image_to_string(img)
        result = translater.translate(text, get_new_key)
        show_translate_box(result, text)
コード例 #4
0
    def on_enter(instance, value):
        """
        The function are triggered by pressing 'enter' while typing
        in input field.
        Shows translation in GUI and updates dictionary.
        """
        lang = instance.parent.sett_man.lang_select.text
        instance.parent.dict_manager.lang = lang
        for _ in range(15):
            try:
                trans_tuple = translate(instance.text.lower(),
                                        lang.lower(),
                                        render=True)
                break
            except AttributeError:
                pass
        else:
            notification.notify(message="", title='Try again!', timeout=1)
            return

        if trans_tuple:
            translation = trans_tuple.translations
            if not (instance.parent.sett_man.lang_select.text == "Guess"):
                instance.parent.dict_manager.update_dict(trans_tuple)
        else:
            translation = 'No translation found!'
        instance.parent.trans_inst.text = translation
コード例 #5
0
 def _hotkey_action(self):
     """
     Translate word, write results into dictionary and notify user if
     hotkey is pressed.
     """
     word = clip.paste()
     # Place requested word in input field.
     self.query_input.text = word
     # Current language
     self.dict_manager.lang = self.sett_man.lang_select.text
     # Translate word.
     for _ in range(10):
         try:
             trans_tuple = translate(word.lower(),
                                     self.dict_manager.lang.lower(),
                                     render=True)
             break
         except AttributeError:
             pass
     else:
         notification.notify(message="", title='Try again!', timeout=1)
         return
     if trans_tuple:
         translation = trans_tuple.translations
         if not (self.sett_man.lang_select.text == "Guess"):
             self.dict_manager.update_dict(trans_tuple)
     else:
         translation = 'No translation found!'
     # Show translation in GUI.
     self.trans_inst.text = translation
     # Notification containing translation results.
     notification.notify(message=translation,
                         title=f'Перевод "{word}"',
                         timeout=10)
コード例 #6
0
def trans(lines):
    """
    读取和翻译文件
    :param file_name: 文件名
    :return:
    """
    trans_result = ""
    # TODO 字符串是否是不可改变的?
    waiting_trans = ""
    for line in lines:
        # TODO 改成正则匹配
        if line.lstrip().startswith('*') or line.lstrip().startswith(
                '/*') or line.lstrip().startswith('*/'):
            # 添加当前行
            trans_result += line
            waiting_trans += line
        else:
            # 查询翻译结果
            if len(waiting_trans) != 0:
                # 查看第一行注释开头的空格数, 因为有可能是\t制表符
                space_index = waiting_trans.index('/')
                space_content = waiting_trans[0:space_index]
                deco = decorator.before_trans(waiting_trans)
                # 添加异常处理是为了定位异常来源
                try:
                    trans_res = translate(deco)
                    # 添加翻译结果
                    trans_result += decorator.after(trans_res, space_content)
                except json.decoder.JSONDecodeError as e:
                    print("翻译内容是:")
                    print(deco)
                    raise e

            # 添加不用翻译的当前行
            trans_result += line
            # 待翻译置为空
            waiting_trans = ""
    return trans_result
コード例 #7
0
ファイル: main.py プロジェクト: madss/hammyprototype
import argparse
from parser import parse
from prettyprinter import prettyprint
from translater import translate
from vm import HammyVM, init, run

parser = argparse.ArgumentParser(description='Hammy interpreter')
parser.add_argument('-p', '--prettyprint', action='store_true')
parser.add_argument('-d', '--decompile', action='store_true')
parser.add_argument('-t', '--trace', action='store_true')
parser.add_argument('file', nargs='?')
args = parser.parse_args()

if args.file:
  src = open(args.file).read()
else:
  src = sys.stdin.read()

vm = HammyVM()
init(vm)
ast = parse(src)
if ast is not None:
  if args.prettyprint:
    print 'Parsed code:'
    print(prettyprint(ast))
    print
  if args.decompile:
    print 'Bytecode:'
  func = translate(ast, args.decompile)
  run(vm, func, args.trace)
コード例 #8
0
# -*- coding: utf-8 -*-

import argparse

import trainer
import translater

parser = argparse.ArgumentParser(
    description='LInput: Pinyin to Chinese; Author: Chenggang Zhao, CST 75')
parser.add_argument('--train',
                    type=str,
                    default='',
                    help='Training dataset config path')
parser.add_argument('--test', type=str, default='', help='Test condig path')
parser.add_argument('--input',
                    type=str,
                    default='',
                    help='Input file path for test mode')
parser.add_argument('--output',
                    type=str,
                    default='',
                    help='Output file path for test mode')

options = parser.parse_args()
if options.train != '':
    trainer.train(options.train)

if options.test != '':
    translater.translate(options.test, options.input, options.output)
コード例 #9
0
refresh_key_time = 60.0
refresh_time_remain = refresh_key_time
get_new_key = False

print("复制需要翻译的文本,或者按Ctrl+>截屏并选取需要翻译的区域")
while True:
    time.sleep(0.01)
    if not get_new_key:
        refresh_time_remain -= 0.01
        if refresh_time_remain <= 0.0:
            get_new_key = True
    text = pyperclip.paste()
    if text != previous_text:
        previous_text = text
        result = translater.translate(text)
        show_translate_box(result)
        continue
    if not keyboard.check(keyboard.VK_CODE["."]):
        previous_key_status = False
        continue
    if previous_key_status:
        continue
    previous_key_status = True
    if not keyboard.check(keyboard.VK_CODE["left_control"]):
        continue
    translate_screenshot(get_new_key)
    if get_new_key:
        get_new_key = False
        refresh_time_remain = refresh_key_time