def read_building(): wb = xlrd.open_workbook('temp/building.xlsx') sh = wb.sheet_by_index(0) rid = str(uuid.uuid1()).replace('-', '') rname = '院区建筑' rcode = '000001000088' print(sql_prefix) print( '(\'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\'){}' .format(rid, pinyin.get_initial(rname, '').upper(), rname, '402881e6415444f6014154db5e150000', '1', rname, '0', pinyin.get(rname, format='strip'), pinyin.get_initial(rname, ''), rcode, ',')) for rx in range(2, sh.nrows): cname = sh.cell_value(rx, 1) clay = int(sh.cell_value(rx, 3)) remark = '共%d层' % clay if sh.row(rx)[2].ctype != 0: remark = '%s[%s]' % (sh.row(rx)[2].value, remark) print( '(\'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\'),' .format( str(uuid.uuid1()).replace('-', ''), pinyin.get_initial(cname, '').upper(), cname, rid, '1', remark, '0', pinyin.get(cname, format='strip'), pinyin.get_initial(cname, ''), rcode + ('%06d' % (rx - 1))))
def read_category(): wb = xlrd.open_workbook('temp/goods-list.xlsx') rid = str(uuid.uuid1()).replace('-', '') rname = '商品类别' rcode = '000001000089' print(sql_prefix) print( '(\'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\'){}' .format(rid, pinyin.get_initial(rname, '').upper(), rname, '402881e6415444f6014154db5e150000', '1', rname, '0', pinyin.get(rname, format='strip'), pinyin.get_initial(rname, ''), rcode, ',')) for s in range(wb.nsheets): sh = wb.sheet_by_index(s) print( '(\'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\', \'{}\'),' .format( str(uuid.uuid1()).replace('-', ''), pinyin.get_initial(sh.name, '').upper(), sh.name, rid, '1', sh.name, '0', pinyin.get(sh.name, format='strip'), pinyin.get_initial(sh.name, ''), rcode + ('%06d' % (s + 1))))
def getStrAllAplha(str, sty): if sty == 'U': return pinyin.get_initial(str, delimiter="").upper() elif sty == 'L': return pinyin.get_initial(str, delimiter="").lower() else: return str
def create_cit(self): from Linjia.models import City as CityModel import json json_file = 'Linjia/models/cities.txt' import pinyin with open(json_file, 'r') as rf: content = json.load(rf) print(content) provinces = content.get('provinces') for province in provinces: citys = province.get('citys') for city in citys: provinceName = province.get('provinceName') cityName = city.get('citysName') c = CityModel() c.Cityid = str(uuid.uuid4()) c.Cityprovincenum = pinyin.get(provinceName, format="numerical") c.Citynum = str( pinyin.get_initial(pinyin.get_initial( provinceName)).replace(' ', '') + '-' + str(pinyin.get(cityName[:-1], format="numerical"))) c.Cityname = cityName c.Cityprovincename = provinceName self.session.add(c) self.session.commit()
def test_get_initial(self): self.assertEqual( pinyin.get_initial(u'你好'), 'n h') self.assertEqual( pinyin.get_initial(u'你好吗?'), 'n h m') self.assertEqual( pinyin.get_initial(u'你好吗?'), u'n h m') self.assertEqual( pinyin.get_initial('你好'.decode('utf-8')), 'n h')
def getStrAllAplha(str): jsonKey = "" Aplha = pinyin.get_initial(str, delimiter="").upper() jsonKeyList = re.findall(r'[A-Z]+', Aplha) for key in jsonKeyList: jsonKey += key return jsonKey
def convert_name(data_file): import pinyin with open(data_file, encoding='utf-8') as f: names = f.readlines() return list( map(lambda name: pinyin.get_initial(name[:-1]).split(' '), names))
def get_pinyin_prefix(str): if (str is None): return '' str = str.strip() if (str == 'None' or str == ''): return '' return pinyin.get_initial(str,delimiter='').upper()
def write_love_author(): db = DB() with Path('./initial-data.json').open('rb') as f: data = json.loads(f.read(), encoding='utf-8') love_author_data = data['love_author'].split(',') db.cursor.execute(''' CREATE TABLE IF NOT EXISTS `author` ( `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `initial_pinyin` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT '', `url` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT '', `area` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT '', `birthday` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT '', `description` text CHARACTER SET utf8 COLLATE utf8_unicode_ci, `status` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ''') db.cursor.execute(''' CREATE TABLE IF NOT EXISTS `musics` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT '', `author` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT '', `path` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `url` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `update_date` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ''') sql = 'INSERT IGNORE INTO `author` (name, initial_pinyin, status) VALUES (%s, %s, %s)' db.cursor.executemany(sql, [(x, pinyin.get_initial(x[0]).lower(), 0) for x in love_author_data])
def processData(month): path = './data_all/{}'.format(month) imgPath = './img' df = readData('{0}/cz_data_{1}.xls'.format(path, month), ['1','2','3']) df['c'] = df['1'].apply(lambda x: [item.strip() for item in x.split()]) df['1'] = df['c'].apply(lambda x: ' '.join(x)) sourceList = list(set(df['3'])) criterion = df['c'].map(rule) for d in ['pos', 'neg']: makeDir('/'.join([path, d])) makeDir('/'.join([imgPath, '..', month])) makeDir('/'.join([imgPath, '..', month, d])) for src in sourceList: makeDir('/'.join([imgPath, '..', month, d, py.get(src, format='strip')])) for src in sourceList: sdf = df[df['3'] == src] pos = sdf[~criterion].drop('c', axis=1) neg = sdf[criterion].drop('c', axis=1) srcName = py.get_initial(src, '') pos.to_csv('{0}/pos/{1}_pos_{2}.tsv'.format(path, month, srcName), sep='\t', index=False) neg.to_csv('{0}/neg/{1}_neg_{2}.tsv'.format(path, month, srcName), sep='\t', index=False) posPicNameList = [''.join([imgPath, '/', x, '.jpg']) for x in pos['1'].tolist()] negPicNameList = [''.join([imgPath, '/', x, '.jpg']) for x in neg['1'].tolist()] copyFiles(posPicNameList, '/'.join([imgPath, '..', month, 'pos', py.get(src, format='strip')])) copyFiles(negPicNameList, '/'.join([imgPath, '..', month, 'neg', py.get(src, format='strip')]))
def assembly(self, imgs, categorys): print('Assembly data begins...') results = [] wb = xlrd.open_workbook('sources/data-2019.10.31.xlsx') total = 0 for si in range(wb.nsheets): sh = wb.sheet_by_index(si) rows = sh.nrows - 2 total += rows category = categorys[sh.name] prefix = pinyin.get_initial(sh.name, '').upper() print('************* %s: %drows *************' % (sh.name, rows)) for ri in range(2, sh.nrows): ind = int(sh.cell_value(ri, 0)) name = sh.cell_value(ri, 1).strip() unit = sh.cell_value(ri, 2).strip() price = sh.cell_value(ri, 3) ptype = sh.row(ri)[3].ctype if ptype == 1: price = price.strip() yind = price.find('元') if yind != -1: price = float(price[:yind]) else: price = 0.0 elif ptype == 0: price = 0.0 imgpath = None try: imgpath = imgs['%s%d' % (pinyin.get(sh.name[:2], format='strip'), ind)] except Exception as e: print('Image not found: %s(%s)' % (name, e)) row = { 'id': str(uuid.uuid1()).replace('-', ''), 'numeration': '%s%06d' % (prefix, ind), 'name': name, 'img': imgpath, 'price': price, 'unit': unit, 'specs': '%.2f/%s' % (price, unit), 'amount': 0, 'category': category, 'enabled': 1, 'create_by': 'admin', 'create_time': datetime.datetime.now() } results.append(row) print('End of assembly data. Total: %d rows.' % total) return results
def get_pinyin_(citys, sp_city): '''@author:李鑫 @data:2019/8/31 获得城市的全拼 ''' for i in citys: if i not in sp_city: city_pin.append(pinyin.get_initial(i, delimiter=''))
def add(char_han, symbol, mode): #中文意思 符号 模式(1为全拼,2为首字母,或者直接输入缩写) global pinyin_dict, han_dict if mode == '1': pinyin_char = pinyin.get(char_han.split('-')[1], format='strip') pinyin_type = pinyin.get_initial(char_han.split('-')[0]).replace( " ", '') pinyin_dict['.' + pinyin_type + '-' + pinyin_char] = symbol han_dict[char_han + symbol] = '.' + pinyin_type + '-' + pinyin_char elif mode == '2': pinyin_char = pinyin.get_initial(char_han).replace(' ', '') pinyin_dict['.' + pinyin_char] = symbol han_dict[char_han + symbol] = '.' + pinyin_char else: pinyin_type = pinyin.get_initial(char_han.split('-')[0]).replace( " ", '') pinyin_dict['.' + pinyin_type + '-' + mode] = symbol han_dict[char_han + symbol] = '.' + pinyin_type + '-' + mode
def process_name(self, name): name_pinyin = pinyin.get(name, format="strip", delimiter=" ") name_initial = ''.join(pinyin.get_initial(name).split()) name_initial_upper = ''.join(pinyin.get_initial(name).split()).upper() name_family = name_pinyin.split()[0] name_family_i = name_pinyin.split()[0].capitalize() name_last = ''.join(name_pinyin.split()[1:]) name_fl = name_pinyin.split()[0] + ''.join(pinyin.get_initial(name).split()[1:]) if name[:2] in ['欧阳', '司徒', '南宫', '夏侯', '西门', '公孙', '司马', '诸葛', '皇甫']: name_family = ''.join(name_pinyin.split()[0:1]) name_last = ''.join(name_pinyin.split()[1:]) name_fl = name_pinyin.split()[0] + ''.join(pinyin.get_initial(name).split()[2:]) name_pinyin = ''.join(name_pinyin.split()) name_result = [name_pinyin, name_family, name_last, name_initial, name_initial_upper, name_fl, name_family_i] return name_result
def read_goods(): categorys = { '商品类别': '3e241446adb611e98258000ec6c11a0e', '水果': '3e24b09eadb611e98196000ec6c11a0e', '粮油副食': '3e24b09fadb611e9b163000ec6c11a0e', '成品菜': '3e24b0a0adb611e994da000ec6c11a0e', '肉蛋水产': '3e24b0a1adb611e9ae17000ec6c11a0e', '速食零食': '3e24b0a2adb611e9b7e3000ec6c11a0e', '牛奶冰品': '3e24b0a3adb611e9984b000ec6c11a0e', '酒水饮料': '3e24b0a4adb611e9a1c7000ec6c11a0e' } datas = {} wb = xlrd.open_workbook('temp/goods-list.xlsx') for i in range(wb.nsheets): sh = wb.sheet_by_index(i) datas[sh.name] = [] numer_perfix = pinyin.get_initial(sh.name, '').upper() for rx in range(2, sh.nrows): if sh.row(rx)[0].ctype != 0: # if sh.ncols > 4 and sh.row(rx)[4].ctype != 0: # if sh.ncols > 4: # print(sh.cell_value(rx, 1) + ', ' + str(sh.row(rx)[4].ctype)) price = sh.cell_value(rx, 3) unit = sh.cell_value(rx, 2) if sh.row(rx)[3].ctype == 1 and '/' in price: specs = price price = re.findall('\d+\.?\d*', sh.cell_value(rx, 3))[0] # print(sh.name + ',' + sh.cell_value(rx, 1) + ', ' + sh.cell_value(rx, 3)) else: specs = '%.2f元/%s' % (price, unit) img = sheet_images.get('%d_%d' % (i, rx)) # if not img is None: # if i == 6 and rx == 32: # print('%s %d_%d' % (sh.cell_value(rx, 1), i, rx)) item = { 'numeration': '%s%s' % (numer_perfix, (str(rx - 1)).zfill(6)), 'name': sh.cell_value(rx, 1), 'img': img, 'price': price, 'unit': unit, 'specs': specs, 'amount': 50, 'category': categorys[sh.name], 'enabled': 1 } datas[sh.name].append(item) lists.append(item) with open('temp/goods.json', 'w', encoding='utf-8') as f: json.dump(datas, f, indent=2, ensure_ascii=False)
def save(self, *args, **kwargs): if not self.id: self.create_time = timezone.now() self.article_html = markdown.markdown(self.article_md) self.pinyin_title = '' for i in filter( str.isalnum, pinyin.get_initial(self.title, delimiter='')): self.pinyin_title += i super(ArticleModel, self).save(args, kwargs)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.id and not self.name and self.des: self.name = pinyin.get_initial(self.des).replace( " ", "") + "_" + shortuuid.ShortUUID().random(8) super(TableModel, self).save()
def random_name_pinyin(name=''): if name == '': name = random_name() if len(name) == 2: name_pinyin = pinyin.get(name, format='strip') else: name_pinyin = pinyin.get(name[0],format='strip')+pinyin.get_initial(name[1:],delimiter="") print('姓名(拼音):'+name_pinyin) return name_pinyin
def __createContactWidget(self): """ 创建联系人小部件 """ for contactInfo in self.contactInfo_list: contactWidget = ContactWidget(contactInfo, self) self.contactWidget_list.append(contactWidget) # 将联系人小部件及其首字母组成字典添加到列表中 self.contactWidgetDict_list.append({ 'contactWidget': contactWidget, 'firstLetter': pinyin.get_initial(contactInfo['contactName'])[0].upper() })
def import_qingbank_user(filepath=None): import pinyin import xlrd import uuid from dxc.services import api_contact, api_department book = xlrd.open_workbook('d:/2014.xls') sheet = book.sheets()[0] max_row = sheet.nrows print 'Begin init qingbank contact' name_dict = {} # max_row = 3 repeat_id = [] for i in range(1, max_row): print str.format('{0}/{1}', i, max_row) employee_id = sheet.row_values(i)[9].strip() desc = None if employee_id is None or employee_id=='': employee_id = str(uuid.uuid1()) desc = u'非在编人员' dept_name = sheet.row_values(i)[1].strip() duty = sheet.row_values(i)[2].strip() name = sheet.row_values(i)[3].strip() name_pinyin = pinyin.get(name) name_shot = pinyin.get_initial(name, '') mobile = sheet.row_values(i)[4] if isinstance(mobile, float): mobile = str(int(mobile)) mobile.strip() tel = sheet.row_values(i)[5] if isinstance(tel, float): tel = str(int(tel)) tel.strip() fax = sheet.row_values(i)[6] if isinstance(fax, float): fax = str(int(fax)) fax.strip() # 创建到数据库 user = user_datastore.get_user(employee_id + '@qingbank.cn') if user is not None: print 'already exist the same id: ' + user.username user.contact.description = 'dept_name' repeat_id.append(user.username) continue user = user_datastore.create_user(username=employee_id, password=name_pinyin, email=employee_id + '@qingbank.cn') db.session.commit() dept = api_department.first(name=dept_name) if dept is None: dept = api_department.create(name=dept_name) api_contact.create(name=name, name_pinyin=name_pinyin, name_shot=name_shot, user_id=user.id, department_id=dept.id, duty=duty, mobile=mobile, telephone=tel, fax=fax, description=desc) print repeat_id
def get_url_list(): db = MongoClient("localhost", 27017).test3.area result = db.find({'p_id': {'$gt': 1}}) result = list(result) name_list = [] for i in result: the_word = pinyin.get_initial(i['name']) name = ''.join(the_word.split()) name_list.append((name, i['id'])) return generate_url_list(name_list)
def test_init_contact(self): """ 初始化联系信息 """ import xlrd book = xlrd.open_workbook('d:/a.xls') sheet = book.sheets()[0] max_row = sheet.nrows print 'begin init database' name_dict = {} max_row = 3 for i in range(2, max_row): print 'row', i dept = sheet.row_values(i)[1].encode("utf-8").strip() job = sheet.row_values(i)[2].encode("utf-8").strip() name = sheet.row_values(i)[3].encode("utf-8").strip() name_pinyin = pinyin.get(name) name_shot = pinyin.get_initial(name, '') username = name_pinyin mobile = str(sheet.row_values(i)[4]) telephone = str(sheet.row_values(i)[5]) innerphone = str(sheet.row_values(i)[6]) fax = str(sheet.row_values(i)[7]) #去掉那些float的. mobile = self.remove_dot(mobile) telephone = self.remove_dot(telephone) innerphone = self.remove_dot(innerphone) fax = self.remove_dot(fax) #统计重复的名字拼音 if name_pinyin in name_dict: username = username + str(name_dict[name_pinyin]) name_dict[name_pinyin] += 1 pass else: name_dict[name_pinyin]=1 print name, job, mobile, telephone, innerphone, fax, dept, pinyin.get(name), name_shot, username #创建到数据库 user = User.objects.get(username='******'); qbinfo = QBContactInfo(duty=job, mobile=mobile, telephone=telephone, innerphone=innerphone, fax=fax) qbinfo.user = user qbinfo.save() print len(name_dict) print name_dict print 'end'
def __getFirstLetterFirstGroupBox(self): """ 获取首字母对应的第一个分组框 """ letter_list = [] self.groupTitle_dict.clear() for group_dict in self.currentGroupDict_list: group = group_dict["container"] letter = pinyin.get_initial(group.title())[0].upper() letter = "..." if not 65 <= ord(letter) <= 90 else letter # 将字母对应的第一个分组框添加到字典中 if letter not in letter_list: letter_list.append(letter) self.groupTitle_dict[letter] = group
def get_city_letters(city): html = requests.post("https://flights.ctrip.com/itinerary/api/poi/get") first_letter = pinyin.get_initial(city[0:1], delimiter="").upper() groups = ["ABCDEF", "GHIJ", "KLMN", "PQRSTUVW", "XYZ"] #print(first_letter) for i in range(0, len(groups)): if first_letter in groups[i]: #print(groups[i]) cities = json.loads(html.text)["data"][groups[i]][first_letter] for i in range(0, len(cities)): if cities[i]['display'] == city: #print(cities[i]['data']) return cities[i]['data'].split('|')[-1]
def alpha_text(cls, src_text) -> str: """ 获取中文字符串的拼音首字母 :param src_text: :return: """ rt_src_text = cls.any_2_str(src_text) if cls.equal_ignore_case(rt_src_text, ''): return '' else: return pinyin.get_initial(src_text, delimiter="").lower().strip().replace( ' ', '')
def updateAllAlbumCards(self, albumInfo_list: list): """ 更新所有专辑卡 """ oldAlbumInfo_list = [ albumCard.albumInfo for albumCard in self.albumCard_list ] if albumInfo_list == oldAlbumInfo_list: return # 将专辑卡从布局中移除 self.__removeContainerFromVBoxLayout() # 根据具体情况增减专辑卡 newCardNum = len(albumInfo_list) oldCardNum = len(self.albumCard_list) deltaNum = newCardNum - oldCardNum if deltaNum < 0: for i in range(oldCardNum - 1, newCardNum - 1, -1): albumCard = self.albumCard_list.pop() self.hideCheckBoxAni_list.pop() self.albumCardDict_list.pop() self.hideCheckBoxAniGroup.takeAnimation(i) albumCard.deleteLater() elif deltaNum > 0: for albumInfo in albumInfo_list[oldCardNum:]: self.__createOneAlbumCard(albumInfo) QApplication.processEvents() # 更新部分专辑卡 self.albumInfo_list = albumInfo_list iterRange = range(oldCardNum) if deltaNum > 0 else range(newCardNum) for i in iterRange: albumInfo = albumInfo_list[i] album = albumInfo["album"] self.albumCard_list[i].updateWindow(albumInfo) QApplication.processEvents() self.albumCardDict_list[i] = { "albumCard": self.albumCard_list[i], "albumName": album, "year": albumInfo["year"][:4], "songer": albumInfo["songer"], "firstLetter": pinyin.get_initial(album)[0].upper(), } # 重新排序专辑卡 self.setSortMode(self.sortMode) # 根据当前专辑卡数决定是否显示导航标签 self.guideLabel.setHidden(bool(albumInfo_list)) # 更新 "专辑名.歌手名":专辑卡 字典 self.albumSonger2AlbumCard_dict = {} for albumCard in self.albumCard_list: albumInfo = albumCard.albumInfo self.albumSonger2AlbumCard_dict[albumInfo["album"] + "." + albumInfo["songer"]] = albumCard if deltaNum != 0: self.albumNumChanged.emit(newCardNum)
def getEngName3(self): name = pinyin.get(self.ChineseName, format="strip", delimiter=" ") name = name.split(' ') surname = name[0] name = pinyin.get_initial(self.ChineseName) name = name.split(' ') first_name = '' for i in range(1, len(name)): first_name = first_name + name[i] first_name = first_name.strip() for key in self.Polyphone: if key.decode('utf-8') == self.ChineseName[0]: surname = self.Polyphone[key] self.engname3 = first_name + '.' + surname
def get_pinyin_first_alpha(name, n=1): def Q2B(uchar): inside_code = ord(uchar) if inside_code == 12288: # 全角空格直接转换 inside_code = 32 elif (inside_code >= 65281 and inside_code <= 65374): # 全角字符(除空格)根据关系转化 inside_code -= 65248 return chr(inside_code) name = ''.join(Q2B(e) for e in name if e.isalnum()) pre = pinyin.get_initial(name).replace(' ', '') if len(pre) < n: pre = '_' else: pre = pre[:n].upper() return pre
def generate_sn(hanzi): #转成拼音 res = pinyin.get_initial(hanzi) #转成大写 res = res.upper() #只保留数字和字母 nondc = re.compile('[^A-Z0-9_]+') res = nondc.sub('', res) #截短 if len(res) > 2: res = res[:2] #10位时间戳 res += str(int(time.time())) return res
def __createOneAlbumCard(self, albumInfo: dict): """ 创建一个专辑卡 """ # 实例化专辑卡和动画 albumCard = AlbumCard(albumInfo, self) # 创建动画 hideCheckBoxAni = QPropertyAnimation(albumCard.checkBoxOpacityEffect, b"opacity") self.hideCheckBoxAniGroup.addAnimation(hideCheckBoxAni) self.hideCheckBoxAni_list.append(hideCheckBoxAni) # 将含有专辑卡及其信息的字典插入列表 album = albumInfo["album"] self.albumCard_list.append(albumCard) self.albumCardDict_list.append({ "albumCard": albumCard, "albumName": album, "year": albumInfo["year"][:4], "songer": albumInfo["songer"], "firstLetter": pinyin.get_initial(album[0])[0].upper(), }) self.albumSonger2AlbumCard_dict[albumInfo["album"] + "." + albumInfo["songer"]] = albumCard # 专辑卡信号连接到槽函数 albumCard.playSignal.connect(self.playSignal) albumCard.nextPlaySignal.connect(self.nextPlaySignal) albumCard.saveAlbumInfoSig.connect(self.__saveAlbumInfoSlot) albumCard.deleteCardSig.connect(self.showDeleteOneCardPanel) albumCard.addToPlayingSignal.connect(self.addAlbumToPlayingSignal) albumCard.switchToAlbumInterfaceSig.connect( self.switchToAlbumInterfaceSig) albumCard.checkedStateChanged.connect( self.__albumCardCheckedStateChangedSlot) albumCard.showBlurAlbumBackgroundSig.connect( self.__showBlurAlbumBackground) albumCard.hideBlurAlbumBackgroundSig.connect( self.albumBlurBackground.hide) albumCard.addAlbumToCustomPlaylistSig.connect( self.addAlbumToCustomPlaylistSig) albumCard.addAlbumToNewCustomPlaylistSig.connect( self.addAlbumToNewCustomPlaylistSig) albumCard.showAlbumInfoEditPanelSig.connect( self.__showAlbumInfoEditPanelSlot)
def add_tags(): cfg = {'path': REPO_DIR} repo = ConfigRepo(cfg) for d in repo.downstream: name = d['name'] py = pinyin.get_initial(name).lower() for c in '(),- /': py = py.replace(c, '') print(name, py) d['tags'] = py repo.save('downstream') repo.publish()
def get_url(new_city,sp_city): '''@author:李鑫 @data:2019/9/2 生成链家上具有新房楼盘城市的url ''' new_url=[] for i in new_city: if i not in sp_city: new_url.append("https://%s.fang.lianjia.com/loupan"%pinyin.get_initial(i,delimiter='')) elif i=='重庆': new_url.append("https://cq.fang.lianjia.com/loupan") elif i=='三亚': new_url.append("https://san.fang.lianjia.com/loupan") else: new_url.append("https://%s.fang.lianjia.com/loupan"%pinyin.get(i, format='strip')) print(new_url) return new_url
def initial_value(string): if not string.strip(): return {} key_value = lambda t: re.compile(r'(.*?):(.*)', re.S).findall(t) try: key, value = key_value(string)[0] init_py = pinyin.get_initial(key, delimiter='') if init_py == 'sqr': if pinyin.get(key, delimiter='').endswith('ren'): init_py = '_'.join((init_py, 'person')) else: init_py = '_'.join((init_py, 'day')) return dict(((init_py, value), )) except IndexError: pass return {}
def find_query (self, needle, haystack): try: import pinyin haystack_py = pinyin.get_initial(haystack, '' ) needle_len = len(needle) start = 0 result = [] while True : found = haystack_py.find(needle, start) if found < 0 : break result.append((found, needle_len)) start = found + needle_len return result except : return None
def init_base_data(request): import xlrd import pinyin book = xlrd.open_workbook('d:/a.xls') sheet = book.sheets()[0] max_row = sheet.nrows print 'begin init database' name_dict = {} # max_row = 3 for i in range(2, max_row): print 'row', i dept_name = sheet.row_values(i)[1].encode("utf-8").strip() job = sheet.row_values(i)[2].encode("utf-8").strip() name = sheet.row_values(i)[3].encode("utf-8").strip() name_pinyin = pinyin.get(name) name_shot = pinyin.get_initial(name, '') first_name = name[:2] last_name = name[2:] username = name_pinyin mobile = str(sheet.row_values(i)[4]) telephone = str(sheet.row_values(i)[5]) innerphone = str(sheet.row_values(i)[6]) fax = str(sheet.row_values(i)[7]) #去掉那些float的. mobile = remove_dot(mobile) telephone = remove_dot(telephone) innerphone = remove_dot(innerphone) fax = remove_dot(fax) #统计重复的名字拼音 if name_pinyin in name_dict: username = username + str(name_dict[name_pinyin]) name_dict[name_pinyin] += 1 pass else: name_dict[name_pinyin]=1 # print name, job, mobile, telephone, innerphone, fax, dept_name, pinyin.get(name), name_shot, username #创建部门 dept = None try: dept = QBDepartment.objects.get(dept_name=dept_name) except QBDepartment.DoesNotExist: dept = QBDepartment(dept_name=dept_name) dept.save() #创建用户到数据库 user = User.objects.create_user(username, None, username, first_name=first_name, last_name=last_name); user.save() #创建联系信息 qbinfo = QBContactInfo(name=name, duty=job, mobile=mobile, telephone=telephone, innerphone=innerphone, fax=fax, name_pinyin=name_pinyin, name_shot=name_shot) qbinfo.user = user qbinfo.qbdepartment = dept qbinfo.save() return HttpResponse("OK")
def save(self, *args, **kwargs): name_pinyin = re.sub("[^a-zA-z ]", "", pinyin.get_initial(self.name, "")) self.name_index = name_pinyin[:1].upper() super(Donor, self).save(*args, **kwargs)
def get_pinyin(self, obj): return pinyin.get_initial(obj.displayname)
def test_get_initial(self): self.assertEqual(pinyin.get_initial('你好'), u('n h')) self.assertEqual(pinyin.get_initial('你好吗?'), u('n h m ?')) self.assertEqual(pinyin.get_initial('你好吗?'), u('n h m ?')) self.assertEqual(pinyin.get_initial('你好'), 'n h')
def test_get_initial_with_delimiter(self): self.assertEqual(pinyin.get_initial('你好', "-"), u('n-h')) self.assertEqual(pinyin.get_initial('你好吗?', "-"), u('n-h-m-?')) self.assertEqual(pinyin.get_initial('你好吗?', "-"), u('n-h-m-?'))
def test_get_initial_with_delimiter(self): self.assertEqual(pinyin.get_initial(u'你好', "-"), 'n-h') self.assertEqual(pinyin.get_initial(u'你好吗?', "-"), 'n-h-m') self.assertEqual(pinyin.get_initial(u'你好吗?', "-"), u'n-h-m') self.assertEqual(pinyin.get(u"蛋疼的事情just happened", "-"), u"dan-teng-de-shi-qing-just-happened")