当前位置: 首页>>代码示例>>Python>>正文


Python re.match方法代码示例

本文整理汇总了Python中re.match方法的典型用法代码示例。如果您正苦于以下问题:Python re.match方法的具体用法?Python re.match怎么用?Python re.match使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在re的用法示例。


在下文中一共展示了re.match方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_assignment_map_from_checkpoint

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
    """Compute the union of the current variables and checkpoint variables."""
    assignment_map = {}
    initialized_variable_names = {}

    name_to_variable = collections.OrderedDict()
    for var in tvars:
        name = var.name
        m = re.match("^(.*):\\d+$", name)
        if m is not None:
            name = m.group(1)
        name_to_variable[name] = var

    init_vars = tf.train.list_variables(init_checkpoint)

    assignment_map = collections.OrderedDict()
    for x in init_vars:
        (name, var) = (x[0], x[1])
        if name not in name_to_variable:
            continue
        assignment_map[name] = name
        initialized_variable_names[name] = 1
        initialized_variable_names[name + ":0"] = 1

    return (assignment_map, initialized_variable_names) 
开发者ID:Socialbird-AILab,项目名称:BERT-Classification-Tutorial,代码行数:27,代码来源:modeling.py

示例2: _validate_short_name

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def _validate_short_name(
        self, short_name, flags
    ):  # type: (Optional[str], int) -> None
        if short_name is None:
            if flags & self.PREFER_SHORT_NAME:
                raise ValueError(
                    "The short option name must be given if the option flag PREFER_SHORT_NAME is selected."
                )

            return

        if not isinstance(short_name, basestring):
            raise ValueError(
                "The short option name must be a string. Got: {}".format(
                    type(short_name)
                )
            )

        if not short_name:
            raise ValueError("The short option name must not be empty.")

        if not re.match(r"^[a-zA-Z]$", short_name):
            raise ValueError("The short option name must be exactly one letter.") 
开发者ID:sdispater,项目名称:clikit,代码行数:25,代码来源:abstract_option.py

示例3: __remove_suffixes

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def __remove_suffixes(av_name, label):
        '''Remove AV specific suffixes from given label
           Returns updated label'''

        # Truncate after last '.'
        if av_name in set(['Norman', 'Avast', 'Avira',
                           'McAffee-GW-Edition', 'McAffee', 'Kaspersky',
                           'ESET-NOD32', 'Fortinet', 'Jiangmin', 'Comodo',
                           'GData', 'Avast', 'Sophos',
                           'TrendMicro-HouseCall', 'TrendMicro',
                           'NANO-Antivirus', 'Microsoft']):
            label = label.rsplit('.', 1)[0]

        # Truncate after last '.' 
        # if suffix only contains digits or uppercase (no lowercase) chars
        if av_name == 'AVG':
            tokens = label.rsplit('.', 1)
            if len(tokens) > 1 and re.match("^[A-Z0-9]+$", tokens[1]):
                label = tokens[0]

        # Truncate after last '!'
        if av_name == 'Agnitum':
            label = label.rsplit('!', 1)[0]

        return label 
开发者ID:Cisco-Talos,项目名称:BASS,代码行数:27,代码来源:avclass_common.py

示例4: decrypt

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def decrypt(data: str, encryption_key: str = None, resource_type: str = None):
    """
    解密资源标识符

    :param data: 加密后的字符串
    :param encryption_key: 可选的 key
    :param resource_type: 验证资源类型(student、teacher、klass、room)
    :return: 资源类型和资源ID
    """
    if not encryption_key:
        encryption_key = get_config().RESOURCE_IDENTIFIER_ENCRYPTION_KEY

    data = _aes_decrypt(encryption_key, data)

    group = re.match(r'^(student|teacher|klass|room);([\s\S]+)$', data)  # 通过正则校验确定数据的正确性
    if group is None:
        raise ValueError('Decrypted data is invalid: %s' % data)
    else:
        if resource_type and group.group(1) != resource_type:
            raise ValueError('Resource type not correspond')
        return group.group(1), group.group(2) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:23,代码来源:encryption.py

示例5: process

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def process(self):
        """Execute the best-match processor for the given media type."""
        proc = None
        ct = self.content_type.value
        try:
            proc = self.processors[ct]
        except KeyError:
            toptype = ct.split('/', 1)[0]
            try:
                proc = self.processors[toptype]
            except KeyError:
                pass
        if proc is None:
            self.default_proc()
        else:
            proc(self) 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:18,代码来源:_cpreqbody.py

示例6: verify

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def verify(self, authenticator_data, client_data_json, signature, user_handle, raw_id, email):
        "Ascertain the validity of credentials supplied by the client user agent via navigator.credentials.get()"
        email = email.decode()
        if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
            raise Exception("Invalid email address")
        client_data_hash = hashlib.sha256(client_data_json).digest()
        client_data = json.loads(client_data_json)
        assert client_data["type"] == "webauthn.get"
        expect_challenge = self.storage_backend.get_challenge_for_user(email=email, type="authentication")
        assert b64url_decode(client_data["challenge"]) == expect_challenge
        print("expect RP ID:", self.rp_id)
        if self.rp_id:
            assert "https://" + self.rp_id == client_data["origin"]
        # Verify that the value of C.origin matches the Relying Party's origin.
        # Verify that the RP ID hash in authData is indeed the SHA-256 hash of the RP ID expected by the RP.
        authenticator_data = AuthenticatorData(authenticator_data)
        assert authenticator_data.user_present
        credential = self.storage_backend.get_credential_by_email(email)
        credential.verify(signature, authenticator_data.raw_auth_data + client_data_hash)
        # signature counter check
        return {"verified": True} 
开发者ID:pyauth,项目名称:pywarp,代码行数:23,代码来源:rp.py

示例7: parse_text

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def parse_text(self,txt):
        err=udpipe.ProcessingError()
        tokenized=""
        current_block=[]
        for line in txt.split("\n"):
            if re.match(comment_regex, line.lstrip()): # comment line
                if current_block:
                    tokenized+=self.pipeline.process("\n".join(current_block),err)
                    current_block=[]
                tokenized+=re.sub(comment_regex, "# ", line.lstrip()+"\n")
                continue
            # normal text line, save to current block to be tokenized
            current_block.append(line)
        if current_block:
            tokenized+=self.pipeline.process("\n".join(current_block),err)
        return tokenized 
开发者ID:TurkuNLP,项目名称:Turku-neural-parser-pipeline,代码行数:18,代码来源:tokenizer_udpipe_mod.py

示例8: launch

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def launch(args,q_in,q_out):
    start=time.time()
    total_parsed_trees=0
    total_parsed_tokens=0
    next_report=start+10.0 #report every 10sec at most
    while True:
        jobid,txt=q_in.get()
        if jobid=="FINAL":
            print("Output exiting",file=sys.stderr,flush=True)
            return
        total_parsed_trees+=sum(1 for line in txt.split("\n") if line.startswith("1\t"))
        total_parsed_tokens+=sum(1 for line in txt.split("\n") if re.match(token_regex, line))
        if total_parsed_trees>0 and time.time()>next_report:
            time_spent=time.time()-start
            print("Runtime: {}:{} [m:s]  Parsed: {} [trees], {} [tokens]  Speed: {} [trees/sec]  {} [sec/tree] {} [tokens/sec]".format(int(time_spent)//60,int(time_spent)%60,total_parsed_trees,total_parsed_tokens, total_parsed_trees/time_spent,time_spent/total_parsed_trees, total_parsed_tokens/time_spent) ,file=sys.stderr,flush=True)
            next_report=time.time()+10
        print(txt,end="",flush=True) 
开发者ID:TurkuNLP,项目名称:Turku-neural-parser-pipeline,代码行数:19,代码来源:output_mod.py

示例9: sentenceToIndex

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def sentenceToIndex(sentence, word2idx, maxLen):
    """
    将句子分词,并转换成embeddings列表的索引值

    :param sentence: 句子
    :param word2idx: 词语的索引
    :param maxLen: 句子的最大长度
    :return: 句子的词向量索引表示
    """
    unknown = word2idx.get("UNKNOWN", 0)
    num = word2idx.get("NUM", len(word2idx))
    index = [unknown] * maxLen
    i = 0
    for word in jieba.cut(sentence):
        if word in word2idx:
            index[i] = word2idx[word]
        else:
            if re.match("\d+", word):
                index[i] = num
            else:
                index[i] = unknown
        if i >= maxLen - 1:
            break
        i += 1
    return index 
开发者ID:shuaihuaiyi,项目名称:QA,代码行数:27,代码来源:qaData.py

示例10: parse

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def parse(self, line):
        if line.strip() == '':
            return

        if re.match(r'^[0-9]+_[0-9]+\t[0-9]+\t[0-9\.]+\t[^\t]+\t[^\t]+$', line):
            scaffoldId = int(re.sub(r'^([0-9]+)_[0-9]+\t[0-9]+\t[0-9\.]+\t[^\t]+\t[^\t]+$',r'\1' ,line))
            contigId = int(re.sub(r'^[0-9]+_([0-9]+)\t[0-9]+\t[0-9\.]+\t[^\t]+\t[^\t]+$',r'\1' ,line))
            ncbid = int(re.sub(r'^[0-9]+_[0-9]+\t([0-9]+)\t[0-9\.]+\t[^\t]+\t[^\t]+$',r'\1' ,line))
            weight = float(re.sub(r'^[0-9]+_[0-9]+\t[0-9]+\t([0-9\.]+)\t[^\t]+\t[^\t]+$',r'\1' ,line))
            source = str(re.sub(r'^[0-9]+_[0-9]+\t[0-9]+\t[0-9\.]+\t([^\t]+)\t[^\t]+$',r'\1' ,line))
            tag = str(re.sub(r'^[0-9]+_[0-9]+\t[0-9]+\t[0-9\.]+\t[^\t]+\t([^\t]+)$',r'\1' ,line))

        if ncbid != 1:
            taxPathDict = self.taxonomy.getPathToRoot(ncbid)
            if taxPathDict is not None and taxPathDict.keys() >= 1:
                self.sequences.setCandidateTaxonomyPath(contigId, scaffoldId, taxPathDict, weight, source, tag)
                self.assignedIdList.append(contigId)
            else:
                sys.stderr.write(str('No taxonomic path found for ncbid: ' + str(ncbid))) 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:21,代码来源:analysis_mg.py

示例11: __init__

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def __init__(self, line):
        tokens = line.split(',')
        self._threshold = float(re.sub(r'^([^\t]+)\t[^\t]+\t.*', r'\1', tokens[0]))
        tokens[0] = re.sub(r'^[^\t]+\t[^\t]+\t(.*)', r'\1', tokens[0])
        self.groupIdCount = 0
        self.seqNameToGroupId = dict([])
        self.groupIdToSeqNameSet = dict([])
        for token in tokens:
            names = token.split('\t')
            self.groupIdToSeqNameSet[self.groupIdCount] = set([])
            for name in names:
                #print name
                if re.match(r'^[0-9]+_.*$', name):
                    seqName = re.sub(r'^([0-9]+_[0-9]+)_.*$',r'\1', name)
                    self.seqNameToGroupId[seqName] = self.groupIdCount
                    self.groupIdToSeqNameSet[self.groupIdCount].add(seqName)
            self.groupIdCount += 1 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:19,代码来源:cluster.py

示例12: _get_variable_name

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def _get_variable_name(self, param_name):
        """Get the variable name from the tensor name."""
        m = re.match("^(.*):\\d+$", param_name)
        if m is not None:
            param_name = m.group(1)
        return param_name 
开发者ID:Socialbird-AILab,项目名称:BERT-Classification-Tutorial,代码行数:8,代码来源:optimization.py

示例13: assert_rank

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def assert_rank(tensor, expected_rank, name=None):
    """Raises an exception if the tensor rank is not of the expected rank.

    Args:
      tensor: A tf.Tensor to check the rank of.
      expected_rank: Python integer or list of integers, expected rank.
      name: Optional name of the tensor for the error message.

    Raises:
      ValueError: If the expected shape doesn't match the actual shape.
    """
    if name is None:
        name = tensor.name

    expected_rank_dict = {}
    if isinstance(expected_rank, six.integer_types):
        expected_rank_dict[expected_rank] = True
    else:
        for x in expected_rank:
            expected_rank_dict[x] = True

    actual_rank = tensor.shape.ndims
    if actual_rank not in expected_rank_dict:
        scope_name = tf.get_variable_scope().name
        raise ValueError(
            "For the tensor `%s` in scope `%s`, the actual rank "
            "`%d` (shape = %s) is not equal to the expected rank `%s`" %
            (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank))) 
开发者ID:Socialbird-AILab,项目名称:BERT-Classification-Tutorial,代码行数:30,代码来源:modeling.py

示例14: getAnnotations

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def getAnnotations(self, chrom, start, end, clip=False, extension=1000000):
        chrom = self.fixChromFormat(chrom)
        
        lines = self.tabix.fetch(chrom, max(0, start-extension), end+extension)

        transcriptsToLines = collections.defaultdict(list)

        for i, line in enumerate(lines):
            if len(line) < 2:
                continue    

            try:            
                tx = re.match(RE_TRANSCRIPT, line).group(1)
            except AttributeError:
                tx = "anno{}".format(i)


            transcriptsToLines[tx].append(line)

        genes = []
        for transcript, lines in transcriptsToLines.items():
            genes.append(GTFGene(lines))

        if extension > 0:
            genes = [gene for gene in genes if not (end<gene.start or start>gene.end)]#start<=gene.start<=end or start<=gene.end<=end)]

        if clip:
            for gene in genes:
                gene.clip(start, end)

        return genes 
开发者ID:svviz,项目名称:svviz,代码行数:33,代码来源:gff.py

示例15: _validate_long_alias

# 需要导入模块: import re [as 别名]
# 或者: from re import match [as 别名]
def _validate_long_alias(self, alias):  # type: (str) -> None
        if not alias[:1].isalpha():
            raise ValueError("A long option alias must start with a letter.")

        if not re.match("^[a-zA-Z0-9\-]+$", alias):
            raise ValueError(
                "A long option alias must contain letters, digits and hyphens only."
            ) 
开发者ID:sdispater,项目名称:clikit,代码行数:10,代码来源:command_option.py


注:本文中的re.match方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。