コード例 #1
0
def getWeather(CITYCODE):

    baseUrl = 'http://d1.weather.com.cn/dingzhi/'
    t = str(time.time()).split('.')[0]
    url = baseUrl + CITYCODE + '.html?_=' + t
    header = {
        'Referer': 'http://www.weather.com.cn/weather/' + CITYCODE + '.shtml', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'
    }

    res = requests.get(url, headers = header)
    res = res.text.encode(res.encoding)
    res = res.decode('utf-8')

    res = res.split('var')[1]
    res = res.split('=')[-1].strip(';')
    res_json = json.loads(res)

    weatherinfo = res_json['weatherinfo']
    city = weatherinfo['cityname']
    temp1 = int(weatherinfo['temp'].strip('℃'))
    temp2 = int(weatherinfo['tempn'].strip('℃'))
    top = temp1 if temp1 > temp2 else temp2
    down = temp2 if temp1 > temp2 else temp1
    top = cn2an.an2cn(str(top)) + '度'
    down = cn2an.an2cn(str(down)) + '度'
    wind = weatherinfo['wd']
    ws = weatherinfo['ws']
    if '<' in ws:
        ws = ws.replace('<','小于')
    if '-' in ws:
        ws = ws.replace('-', '到')
    weather = weatherinfo['weather']

    today = '今天{}{}, 最高温度{},最低温度{},{},{}'.format(city, weather, top, down, wind, ws)
    return today
コード例 #2
0
    def createlygov(data):

        areaName = data["areaName"]
        if (any(chr.isdigit() for chr in areaName)):
            num = ''.join([x for x in areaName if x.isdigit()])
            print(cn2an.an2cn(num, "low"))
            areaName = areaName.replace(num, cn2an.an2cn(num, "low"))
            print("after replace", areaName)

        # 搜尋選區
        sqlstr = "select id from area where name = \"%s\" " % areaName
        print(sqlstr)
        areaName = DB.execution(DB.select, sqlstr)
        areaName = areaName.get("data")[0].get("id")
        print(areaName)

        # 搜尋黨籍
        sqlstr = "select id from party where name = \"%s\" " % data["party"]
        print(sqlstr)
        party = DB.execution(DB.select, sqlstr)
        party = party.get("data")[0].get("id")
        print(party)
        sqlstr = (
            "insert into politician(term,name,sex,experience,tel,degree,address,party_id,photo,area_id,position_id) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')"
            % (data["term"], data["name"], data["sex"], data["experience"],
               data["tel"], data["degree"], data["addr"], party,
               data["picUrl"], areaName, "1"))
        print(sqlstr)
        DB.execution(DB.create, sqlstr)
        # 搜尋政治人物id回傳
        # 搜尋委員會
        comms = data["committee"].split(";")
        sqlstr = (
            "select id from politician where name='%s' and term='%s'  and position_id='%s'"
            % (data["name"], data["term"], 1))
        print(comms)
        print(sqlstr)
        politid = DB.execution(DB.select, sqlstr)

        politid = politid.get("data")[0].get("id")
        for i in comms:
            if (i != ""):
                session = i.split(":")[0]

                sqlstr = ("select id from committee where name= '%s'" %
                          i.split(":")[1])
                print(sqlstr)
                committee = DB.execution(DB.select, sqlstr)
                print(committee)
                committee = committee.get("data")[0].get("id")
                sqlstr = (
                    "insert into legislatorcol (politician_id,committee_id,sessions) values('%s','%s','%s')"
                    % (politid, committee, session))
                print(sqlstr)
                DB.execution(DB.create, sqlstr)
コード例 #3
0
def replace_num(str):
    if isinstance(str, float):
        return ""
    start = -1
    new_str = ""
    for i in range(len(str) - 1):
        # print(str[i])
        # print(str[i].isnumeric())
        if str[i].isdigit():
            # print(str[i])
            if start != -1 and str[i + 1].isdigit():
                continue
            if start == -1:
                start = i
            if start != -1 and str[i + 1].isdigit() is False:
                try:
                    num = cn2an.an2cn(str[start:i + 1], 'low')
                except ValueError:
                    num = str[start:i + 1]
                start = -1
                new_str = new_str + num
            # if str[i + 1] != '年' and str[i + 1] != '月' and str[i + 1] != '日' and str[i + 1] != '天' and str[i] != ':' and \
            #         str[i + 1] != '小' and str[i + 1] != '时' and str[i + 1] != '分' and str[i + 1] != '秒' and \
            #         str[i + 1].isalpha() is False and str[i + 1].isdigit() is False and start != -1:
            #     print(str[start:i+1])
            #     num = cn2an.an2cn(str[start:i+1], 'low')
            #
            #     start = -1
            #     new_str = new_str + num
        else:
            new_str = new_str + str[i]
    return new_str
コード例 #4
0
 def _get_raw_audio(self, x):
     self.progress = 0.0
     x = XiSpeechSynthesizer.convert_to_simplified.convert(
         x)  # convert text to simplified chinese
     # MODE 1: convert numbers to chinese characters. can convert decimal and negative numbers correctly.
     x = sub(XiSpeechSynthesizer.regex, lambda m: an2cn(m.group()), x)
     # MODE 2: convert numbers to chinese characters. can convert fractional numbers and dates correctly.
     # x = transform(x, "an2cn")  # convert numbers to chinese characters
     x = x.translate(XiSpeechSynthesizer.translation
                     )  # convert all punctuations to full stops.
     x = x.lower()
     x = pinyin(x, style=Style.TONE3)
     x = XiSpeechSynthesizer.reshape_array(x)
     # audio = AudioSegment.empty()
     length = len(x)
     if length == 0:
         self.progress = 0.9
         return AudioSegment.empty(), []
     self.steps_required = 2**(floor(
         log2(length)) + 1) - 1 + 2 * (length - 2**floor(log2(length)))
     self.current_step = 0
     audio, error_message = self._recursive_synthesize(x, 0, length)
     audio += AudioSegment.silent(duration=50)
     self.progress = 0.9
     return audio, error_message
コード例 #5
0
async def _(session: NLPSession):
    msg = session.msg.strip()
    global tot, lst
    userid = session.event["user_id"]

    groupid = session.event["group_id"]

    if not groupid in group_list:
        return

    #    print("userid=",userid)
    #    print("groupid=",groupid)

    if groupid in lst and lst[groupid] == msg:
        tot[groupid] += 1
    else:
        tot[groupid] = 1

    lst[groupid] = msg

    if tot[groupid] >= 3:
        bot = session.bot
        await session.send(cn2an.an2cn(tot[groupid]) + "连击!")
        await bot.set_group_ban(group_id=groupid,
                                user_id=userid,
                                duration=30 * (2**tot[groupid]))
コード例 #6
0
def convert_arabic_number_to_chinese(word, model="low"):
    """
    阿拉伯数字转中文数字 使用cn2an进行转换 doc: https://github.com/Ailln/cn2an
    example: 1989年 -> 一千九百八十九年  2287 -> 二千二百八十七
    :param word:   待转换的单词字符串
    :param model:  cn2an转换模式 low/up/rmb/direct
    """
    from frame.extension.participle import participle_app

    number_reg_check = "\d+\.?\d*"

    numbers = re.findall(number_reg_check, word)
    numbers.sort(key=lambda x: len(x), reverse=True)

    for number in numbers:
        chinese_number = None
        try:
            chinese_number = cn2an.an2cn(number, model)
        except Exception as e:
            if not isinstance(e, ValueError) and hasattr(
                    participle_app, "logger"):
                participle_app.logger.error(
                    f"convert number {number} except {str(e)}")
            chinese_number = number
        finally:
            if chinese_number != number:
                word = word.replace(number, chinese_number)

    return str(word)
コード例 #7
0
def index():
    total = total_money(session['token'])
    file = io.BytesIO()
    workbook = xlsxwriter.Workbook(file)
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, '单价')
    worksheet.write(0, 1, '数量')

    random.seed(session['token'])
    cut = set()
    while len(cut) < 999:
        n = random.randrange(1, total)
        cut.add(n)
    cut = [0] + sorted(cut) + [total]

    row = 1
    for start, end in zip(cut[:-1], cut[1:]):
        total_price = end - start
        price = total_price
        count = random.randrange(2, 11)
        if price % count == 0:
            price //= count
        else:
            count = 1
        assert count * price == total_price
        worksheet.write(row, 0, cn2an.an2cn(price / 100, "rmb"))
        worksheet.write(row, 1, count)
        row += 1
    workbook.close()
    file.seek(0)
    return send_file(file,
                     attachment_filename="bills.xlsx",
                     as_attachment=True)
コード例 #8
0
 def gen_header(self):
     level_dict = {}
     levels = ['名称']
     for item in self.bfs_res:
         key = item.get('level')
         # 0级即是root,从第一级开始统计
         if key and key not in level_dict:
             level_dict[key] = True
             self.level += 1
             levels.append("第%s层级" % cn2an.an2cn(self.level, "low"))
     print(levels)
     return levels
コード例 #9
0
    def get_torrent_name_ptn(self) -> dict:
        search = re.search(PTN, self.torrent_name)
        if search:
            torrent_name_ptn = search.groupdict()
            if torrent_name_ptn.get('season'):
                torrent_name_ptn['season_cn'] = cn2an.an2cn(torrent_name_ptn.get('season'))

            self.torrent_name_ptn = torrent_name_ptn
            return self.torrent_name_ptn

        # 说明种子命名不符合我们的要求
        raise AutoseedStopException('待发布种子 %s 不符合发布文件命名规则,跳过' % (self.torrent_name,))
コード例 #10
0
    def generate_contract(self,workbook,data,lines,recordset,account_move,sale_order):

            format_of_title=workbook.add_format({'font_name':'SimSun','font_size':12,'align':'center','valign':'center','bold':True})
            format_of_table_title=workbook.add_format({'font_name':'SimSun','font_size':11,'align':'left','valign':'vcenter','border': True,'shrink':True})
            format_of_table_head=workbook.add_format({'font_name':'SimSun','font_size':11,'align':'center','valign':'vcenter','border': True})
            format_of_table_content_total=workbook.add_format({'font_name':'SimSun','font_size':11,'align':'center','valign':'vcenter','border': True,'bold':True,'shrink':True})
            format_of_contract_content=workbook.add_format({'font_name':'SimSun','font_size':10,'align':'left','valign':'vcenter','right': True,'text_wrap':True})

            format_of_table_content = workbook.add_format(
                    {'font_name': 'SimSun', 'font_size': 10, 'align': 'center', 'valign': 'vcenter', 'border': True,'text_wrap':True})


            sheet_of_contract=workbook.add_worksheet('国控广西采购合同')

            sheet_of_contract.insert_image(0,0,'/Users/wuhua/GitHub/custom_addons/extending_odoo/images/guokongGX.png',{'x_scale': 1.2, 'y_scale': 1.4})
            sheet_of_contract.merge_range(0,0,0,10,'')
            sheet_of_contract.set_row(0,36)
            row=1
            sheet_of_contract.merge_range(row,0,row,7,'共1页第1页             国药控股广西有限公司购进合同',format_of_title)
            #get the abbreviation_of_patient_name
            abbreviation_of_patient_name_list=pinyin((sale_order.patient_name if sale_order.patient_name != False else 'false'),style=Style.FIRST_LETTER)
            abbreviation_of_patient_name=''
            for alph in abbreviation_of_patient_name_list:
                    abbreviation_of_patient_name+=alph[0]

            sheet_of_contract.merge_range(row, 8, row, 10, '编号:'+account_move.partner_id.abbreviation+'-'+abbreviation_of_patient_name.upper()+'-'+(sale_order.date_of_surgery.strftime("%m%d") if sale_order.date_of_surgery != False else 'false' ) ,format_of_title)

            row+=1

            sheet_of_contract.merge_range(row,0,row,10,'合同有效期至:        年        月        日                 签约地点:广西南宁                        签约时间:        年        月        日',format_of_table_title)
            row+=1
            col=0

            sheet_of_contract.write(row,0,'货品ID',format_of_table_head)
            sheet_of_contract.write(row, 1, '品名', format_of_table_head)
            sheet_of_contract.write(row, 2, '规格', format_of_table_head)
            sheet_of_contract.write(row, 3, '生产厂家', format_of_table_head)
            sheet_of_contract.write(row, 4, '单位', format_of_table_head)
            sheet_of_contract.write(row, 5, '包装', format_of_table_head)
            sheet_of_contract.write(row, 6, '供医院价', format_of_table_head)
            sheet_of_contract.write(row, 7, '供货价', format_of_table_head)
            sheet_of_contract.write(row, 8, '数量', format_of_table_head)
            sheet_of_contract.write(row, 9, '金额', format_of_table_head)
            sheet_of_contract.write(row, 10, '注册证(备案凭证)号', format_of_table_head)
            row+=1

            #write every row
            for rec in recordset:
                    self.write_one_row_of_contract(sheet_of_contract,row,rec,format_of_table_content)
                    row+=1

            #write total of the amount
            #write chinese total
            #sheet_of_contract.merge_range(row, 0, row, 1, '金额合计(大写):', format_of_table_content)
            total_in_chinese=cn2an.an2cn(account_move.amount_total,"rmb")
            sheet_of_contract.merge_range(row, 0, row, 7, '金额合计(大写):'+total_in_chinese, format_of_table_content_total)
            #write total in arab number
            sheet_of_contract.merge_range(row,8,row,9,'金额合计(小写):',format_of_table_content_total)
            sum_range= xl_range(4,9,row-1,9)
            sum_formula='=SUM(%s)' % sum_range
            sheet_of_contract.write(row,10,sum_formula,format_of_table_content_total)
            row+=1
            sheet_of_contract.merge_range(row,0,row,10,'双方经充分协商,签订本合同,共同信守,未尽事宜,按《中华人民共和国合同法》、《质量保证协议》、医疗器械相关法律法规等有关规定执行。',format_of_table_head)
            row+=1
            sheet_of_contract.merge_range(row,0,row,5,'一、质量标准:符合现行器械相关标准,每批来货附合格证或成品检验报告书,进口医疗器械附报关单;包装、标签和说明书应符合国家有关规定和运输要求。',format_of_contract_content)



            return
コード例 #11
0
ファイル: text_utils.py プロジェクト: RonDen/Research
def an_to_cn(string):
    """an to cn"""
    try:
        return str(cn2an.an2cn(string))
    except ValueError:
        return string
コード例 #12
0
ファイル: model2.py プロジェクト: GongCQ/tianchi_nl2sql
def an_to_cn(string):
    try:
        return str(cn2an.an2cn(string))
    except ValueError:
        return string
コード例 #13
0
 def _convert_to_amount_in_word(self, number):
     """Convert number to ``amount in words`` for Chinese financial usage."""
     if not self.check_cn2an():
         return None
     return an2cn(number, 'rmb')
コード例 #14
0
ファイル: utils.py プロジェクト: Hillary060/Text-Based-QA
 def __int2cn(matched):
     if len(matched.group(0)) >= 8:
         # 长度 >= 8的阿拉伯数字不转换
         return matched.group(0)
     else:
         return an2cn(matched.group(0), 'low')
コード例 #15
0
    def generate_xlsx_report(self, workbook, data, lines):





            format_of_title=workbook.add_format({'font_size':14,'align':'center','bold':True})
            format_of_address= workbook.add_format({'font_size': 10, 'align': 'left'})
            format_of_table_head = workbook.add_format({'font_size': 9, 'align': 'center','valign':'vcenter','border':True,'text_wrap':True,'bold':True})
            format_of_table_content = workbook.add_format({'font_size': 9, 'align': 'center','valign':'vcenter','border':True,'text_wrap':True})
            format_of_table_content_date = workbook.add_format({'font_size': 9, 'align': 'center', 'valign': 'vcenter', 'border': True, 'text_wrap': True,'num_format':'yyyy-mm-dd'})
            format_company_info=workbook.add_format({'font_size': 9, 'align': 'left', 'valign': 'vcenter'})
            format_of_table_content_address = workbook.add_format({'font_size': 9, 'align': 'left', 'valign': 'vcenter', 'border': True, 'text_wrap': True})


            #single_record = self.browse(1)
            #self.write_one_row(sheet,4,single_record,format_of_table_content,format_of_table_content_date)
            row=4
            #get current invoice id
            #invoice_id=self.invoice_ids.id

            invoice_id=int(re.findall('\d+',data['data'])[0])
            recordset = self.env['report.outbound.delivery.order'].search([('move_id','=',invoice_id)])

            single_record=recordset[0]
            self.env.cr.execute("SELECT order_line_id FROM sale_order_line_invoice_rel WHERE invoice_line_id=%s",(single_record.id,))
            order_line_list=self.env.cr.fetchall() #fetchall return a list of tuples
            self.ensure_one_for_list(order_line_list)
            order_line_id=order_line_list[0][0]
            sale_order_line= self.env['sale.order.line'].search([('id', '=', order_line_id)])
            sale_order=sale_order_line.order_id

            account_move=self.env['account.move'].browse(invoice_id)

            sheet = workbook.add_worksheet((account_move.invoice_partner_display_name if account_move.invoice_partner_display_name != False else 'false')+' '+(sale_order.patient_name if sale_order.patient_name != False else 'false')+' '+(sale_order.date_of_surgery.strftime("%Y-%m-%d") if sale_order.date_of_surgery != False else 'false' ))

            #sheet = workbook.add_worksheet(account_move.invoice_partner_display_name+' '+sale_order.patient_name+' '+sale_order.date_of_surgery.strftime("%Y-%m-%d"))

            self.write_table_header(sheet,format_of_title,format_of_address,format_of_table_head)



            for record in recordset:
                    self.write_one_row(sheet,row,record,format_of_table_content,format_of_table_content_date)
                    row+=1
                    print('print out delivery for invoice_id=',invoice_id)
                    print('patient name is: ', sale_order.patient_name)
                    print((account_move.invoice_partner_display_name if account_move.invoice_partner_display_name != False else 'false'))


            #write the tail of table
            sheet.merge_range(row,0,row,4,'合计',format_of_table_content)
            sum_range= xl_range(4,9,row-1,9)
            sum_formula='=SUM(%s)' % sum_range
            sheet.merge_range(row, 5, row, 13,sum_formula , format_of_table_content)
            row+=1
            #write chinese total
            sheet.merge_range(row, 0, row, 1, '金额合计(大写):', format_of_table_content)
            total_in_chinese=cn2an.an2cn(account_move.amount_total,"rmb")
            sheet.merge_range(row, 2, row, 13, total_in_chinese, format_of_table_head)
            row+=1
            #write info of our company
            sheet.merge_range(row, 0, row, 13, '公司地址:广西南宁市白沙大道35号南国花园商城D1栋D1-2号、D1-4号房', format_of_table_content_address)
            row+=1
            sheet.write(row, 0, '备注:', format_company_info)
            sheet.merge_range(row, 1, row, 13, '1、本发货单加盖本公司印章方可提货,提货前与仓库联系。', format_company_info)
            row+=1
            sheet.merge_range(row, 1, row, 13, '2、客户提货时请验看货物,出库后不接受无理由退货。', format_company_info)
            row+=1
            sheet.merge_range(row, 1, row, 13, '3、请客户在发货单有效期内提货,如逾期或未提货,须重新办理有关手续,由此产生的一切费用由需方自理。', format_company_info)
            row+=1
            sheet.merge_range(row, 1, row, 13, '4、此发货单一式五联,第一联:存根(白)第二联:结算(粉)第三联:保管(绿)第四联:装货(蓝)。', format_company_info)
            row+=1
            sheet.merge_range(row, 1, row, 13, '5、如有问题,请及时与本公司联系。', format_company_info)
            row+=1
            sheet.merge_range(row, 0, row, 13, '  制单:唐舒恩              提货人:彭军          客户签收:              签收日期:', format_company_info)


        #generate contract with guokongGX
            self.generate_contract(workbook,data,lines,recordset,account_move,sale_order)

            return
コード例 #16
0
ファイル: lm_create.py プロジェクト: LZ-QWQ/QAQQAQ
def digits2ch_assit(matched):
    value = matched.group('value')
    if len(str(value)) > 16: return '一百'  #有毒把?
    return cn2an.an2cn(value, 'low')
コード例 #17
0
    text[0].text = out[0]
    text[1].text = out[1]
    for x in range(cols, all_rows, cols):
        row_cells = table.add_row().cells
        row_cells[0].text = out[x]
        row_cells[1].text = out[x + 1]

    #make the word biger
    for row in table.rows:
        for cell in row.cells:
            paragraphs = cell.paragraphs
            for paragraph in paragraphs:
                for run in paragraph.runs:
                    font = run.font
                    font.size = Pt(14)

    d.save(fileName)


try:
    os.remove('work.docx')
    os.remove('answer.docx')
except:
    pass
for x in range(7):
    subject = blend()
    answer(days=x + 1, subject=subject)
    work('work.docx', subject=subject, heading='第' + an2cn(x + 1) + '天')

printFile('work.docx')
コード例 #18
0
         else:
             r = format(rdigital)
         rm = random.choice(money)
         rstr = rm + r
         # print(rm+r)
     elif rtype == 'contract_number':
         alphabet = 'QWERTYUIOPASDFGHJKLZXCVBNM'
         number = '0123456789'
         seperate = ['', '-', '/', '\\']
         # sep_num = random.randint(1, 3)
         rlen = random.randint(8, 16)
         ralen = random.randint(1, 5)
         idxs = np.random.randint(0, len(alphabet), size=ralen)
         astr = ''.join([alphabet[i] for i in idxs])
         idxs = np.random.randint(0, len(number), size=rlen - ralen)
         nstr = ''.join([number[i] for i in idxs])
         rs = random.choice(seperate)
         rstr = astr + rs + nstr
         # print(rstr)
     elif rtype == 'chinese':
         is_float = random.choice(btype)
         rdigital = random.uniform(0.001, 100000)
         if is_float:
             fint = random.choice([1, 2, 3])
             rdigital = round(rdigital, fint)
         else:
             rdigital = int(rdigital)
         rstr = cn2an.an2cn(rdigital, "rmb")
         # rstr = digital_to_chinese(rdigital)
     wf.write(rstr + '\n')
 wf.close()