當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。