當前位置: 首頁>>代碼示例>>Python>>正文


Python re.split方法代碼示例

本文整理匯總了Python中re.split方法的典型用法代碼示例。如果您正苦於以下問題:Python re.split方法的具體用法?Python re.split怎麽用?Python re.split使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在re的用法示例。


在下文中一共展示了re.split方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: write_version_py

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def write_version_py():
    content = """# GENERATED VERSION FILE
# TIME: {}

__version__ = '{}'
short_version = '{}'
version_info = ({})
"""
    sha = get_hash()
    with open('mmdet/VERSION', 'r') as f:
        SHORT_VERSION = f.read().strip()
    VERSION_INFO = ', '.join(SHORT_VERSION.split('.'))
    VERSION = SHORT_VERSION + '+' + sha

    version_file_str = content.format(time.asctime(), VERSION, SHORT_VERSION,
                                      VERSION_INFO)
    with open(version_file, 'w') as f:
        f.write(version_file_str) 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:20,代碼來源:setup.py

示例2: make_cuda_ext

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def make_cuda_ext(name, module, sources, sources_cuda=[]):

    define_macros = []
    extra_compile_args = {'cxx': []}

    if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':
        define_macros += [('WITH_CUDA', None)]
        extension = CUDAExtension
        extra_compile_args['nvcc'] = [
            '-D__CUDA_NO_HALF_OPERATORS__',
            '-D__CUDA_NO_HALF_CONVERSIONS__',
            '-D__CUDA_NO_HALF2_OPERATORS__',
        ]
        sources += sources_cuda
    else:
        print(f'Compiling {name} without CUDA')
        extension = CppExtension
        # raise EnvironmentError('CUDA is required to compile MMDetection!')

    return extension(
        name=f'{module}.{name}',
        sources=[os.path.join(*module.split('.'), p) for p in sources],
        define_macros=define_macros,
        extra_compile_args=extra_compile_args) 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:26,代碼來源:setup.py

示例3: find_test_path

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def find_test_path(test_file):
    """Searches for the test file and returns the path if found
    As a default, the currend working directory is the top of the search.
    If a directory was provided as part of the argument, the directory will be
    joined with cwd unless it was an absolute path, in which case, the
    absolute path will be used instead. 
    """
    test_file += ".py"
    test_path = os.path.split(test_file)
    top = os.path.join(os.getcwd(), test_path[0])

    for (path, dirs, files) in os.walk(top):
        if test_path[1] in files:
            return  os.path.join(path, test_path[1])
    raise FileNotFoundError("Could not find " + test_path[1] + 
                            "in directory: " + top) 
開發者ID:awslabs,項目名稱:dynamic-training-with-apache-mxnet-on-aws,代碼行數:18,代碼來源:flakiness_checker.py

示例4: basic_tokenizer

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def basic_tokenizer(sentence):
  """Very basic tokenizer: split the sentence into a list of tokens."""
  words = []
  if old_style:
    for space_separated_fragment in sentence.strip().split():
      words.extend(re.split(_OLD_WORD_SPLIT, space_separated_fragment))
    return [w for w in words if w]
  for space_separated_fragment in sentence.strip().split():
    tokens = [t for t in re.split(_WORD_SPLIT, space_separated_fragment) if t]
    first_is_char = False
    for i, t in enumerate(tokens):
      if len(t) == 1 and t in _PUNCTUATION:
        tokens[i] = _CHAR_MARKER + t
        if i == 0:
          first_is_char = True
    if words and words[-1] != _SPACE and (first_is_char or is_char(words[-1])):
      tokens = [_SPACE] + tokens
    spaced_tokens = []
    for i, tok in enumerate(tokens):
      spaced_tokens.append(tokens[i])
      if i < len(tokens) - 1:
        if tok != _SPACE and not (is_char(tok) or is_char(tokens[i+1])):
          spaced_tokens.append(_SPACE)
    words.extend(spaced_tokens)
  return words 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:27,代碼來源:wmt_utils.py

示例5: extract_fields_db2

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def extract_fields_db2(obj, line, field_name_regex):
    line = '#'.join(re.split('\s*#', line))

    last_key = ''
    field_names = re.findall(field_name_regex, line)
    for field in reversed(field_names):
        split_at = line.find(field) + len(field)
        field_name = re.split('\s*:', field)[0]
        # don't overwrite existing fields
        if field_name in obj:
            continue
        else:
            obj[field_name] = ' '.join(line[split_at:].split())
            if not last_key:
                last_key = field_name
        line = line[:split_at - len(field)]
    return last_key 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:19,代碼來源:reportMetrics.py

示例6: _parse_docstring

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def _parse_docstring(self, docstring=''):
        """
        :param docstring:
        :return: (summary, description, schema)
        """
        summary, description, schema = None, None, dict()
        docstring = docstring.strip()

        if '---' in docstring:
            head, yml = re.split(r'\s*---+\s*\n', docstring)
            if yml:
                schema = self.yaml_load(yml) or dict()
        else:
            head = docstring

        if '\n' in head.strip():
            summary, description = map(lambda s: s.strip(), head.split('\n', 1))
        elif head:
            summary = head.strip()

        return summary, description, schema 
開發者ID:Arello-Mobile,項目名稱:py2swagger,代碼行數:23,代碼來源:yamlparser.py

示例7: get_cipher_list

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def get_cipher_list(encryption_mode):
    """
    Get list of ciphers from encryption mode.

    Example:
    get_cipher_list("psk2+tkip+aes") -> ["TKIP", "CCMP"]
    """
    parts = encryption_mode.lower().split('+')
    ciphers = []

    if "tkip" in parts:
        ciphers.append("TKIP")
    if "ccmp" in parts or "aes" in parts:
        ciphers.append("CCMP")

    if len(ciphers) == 0:
        # We need to enable at least one cipher. Most modes default to CCMP
        # except for wpa.
        if parts[0] == "wpa":
            ciphers.append("TKIP")
        else:
            ciphers.append("CCMP")

    return ciphers 
開發者ID:ParadropLabs,項目名稱:Paradrop,代碼行數:26,代碼來源:wireless.py

示例8: __init__

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def __init__(self, name, uiType, size, persistence, familyPrefix, uiParams, tableSize, prefixSymbol, line):
		self.name = name
		self.familyPrefix = familyPrefix or ""
		self.uiType = uiType
		self.prefixSymbol = prefixSymbol
		if self.uiType == "ui_text_edit":
			self.prefixSymbol = "@"
		self.uiParams = uiParams or ""
		self.numElements = size
		self.dimensionsString = size
		self.underscore = ""
		if "," in size:
			self.underscore = "_"
			self.numElements = "*".join(["(%s)" % dim for dim in size.split(",")])
		self.numElements = tryStringEval(self.numElements, line, "UI array size")
		self.persistence = persistence or ""
		self.tableSize = tableSize 
開發者ID:nojanath,項目名稱:SublimeKSP,代碼行數:19,代碼來源:preprocessor_plugins.py

示例9: prefix_with_ns

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def prefix_with_ns(name, namespaces, function_parameter_names=None, force_prefixing=False):
    if not namespaces:
        return name
    function_parameter_names = function_parameter_names or []
    ##name = name.replace('.', '__') # replace . by __

    if name[0] in variable_prefixes:
        prefix, unprefixed_name = name[0], name[1:]
    else:
        prefix, unprefixed_name = '', name

    # if the name consists of multiple parts (eg. myfamily.myvariable extract the first part - myfamily in this example)
    first_name_part = name.split('.')[0]

    # if built-in name or function parameter
    if (unprefixed_name in ksp_builtins.variables_unprefixed or
          name in ksp_builtins.functions or
          name in ksp_builtins.keywords or
          first_name_part in function_parameter_names) and not force_prefixing:
        return name # don't add prefix

    # add namespace to name
    return prefix + '.'.join(namespaces + [unprefixed_name]) 
開發者ID:nojanath,項目名稱:SublimeKSP,代碼行數:25,代碼來源:ksp_compiler.py

示例10: multiRunPostProcessing

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def multiRunPostProcessing(self, PPoutpath, folders):
        outtext = list()
        for folder in folders:
            lines = list()
            with open(os.path.join(folder,'NEIDinfo.txt'), 'r') as g: #Write to file
                lines = g.read().split('\n')[0:-1]
            lines2 = [line.split(',') for line in lines]
            try:
                lines2 = lines2.remove([''])
            except:
                pass
            lines3 = [','.join(line) for line in lines2 if float(line[1]) < 24764.0/6371.0]
            outtext.append('\n'.join(lines3))#OUTTEXT contains a complete list of all sub-neptune detections
        with open(os.path.join(PPoutpath,'NEIDallSubNeptunes.txt'), 'w') as g: #Write to file
            g.write('\n'.join(outtext))
        
        #### Count number of surveys analyzed
        NumAnalyzed = 0
        for folder in folders:
            pklfiles = glob.glob(os.path.join(folder,'*.pkl'))
            NumAnalyzed += len(pklfiles)
        with open(os.path.join(PPoutpath,'NEIDcountFilesAnalyzed.txt'), 'w') as g: #Write to file
            g.write(str(NumAnalyzed)) 
開發者ID:dsavransky,項目名稱:EXOSIMS,代碼行數:25,代碼來源:collateAllUniqueDetections.py

示例11: gist_fetch

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def gist_fetch(query, page_idx, total_items=1000):
    gist_url = "https://gist.github.com/search?utf8=%E2%9C%93&q={}&p={}"
    query = urllib.parse.quote(query)
    gists = []

    try:
        resp = requests.get(gist_url.format(query, page_idx))
        soup = bs4.BeautifulSoup(resp.text, 'html.parser')
        total_items = min(total_items, int(
            [x.text.split()[0] for x in soup.find_all('h3')
                if "gist results" in x.text][0].replace(',', '')))
        gists = [x.get("href") for x in soup.findAll(
                            "a", class_="link-overlay")]
    except IndexError:
        return {"data": None, "total_items": 0}

    return {"data": gists, "total_items": total_items} 
開發者ID:BishopFox,項目名稱:GitGot,代碼行數:19,代碼來源:gitgot.py

示例12: get_max_word_length

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def get_max_word_length(
    string, formatter=None
):  # type: (str, Optional[Formatter]) -> int
    if formatter is not None:
        string = formatter.remove_format(string)

    max_length = 0
    words = re.split("\s+", string)

    for word in words:
        max_length = max(max_length, get_string_length(word))

    return max_length 
開發者ID:sdispater,項目名稱:clikit,代碼行數:15,代碼來源:string.py

示例13: get_max_line_length

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def get_max_line_length(
    string, formatter=None
):  # type: (str, Optional[Formatter]) -> int
    if formatter is not None:
        string = formatter.remove_format(string)

    max_length = 0
    words = re.split("\n", string)

    for word in words:
        max_length = max(max_length, get_string_length(word))

    return max_length 
開發者ID:sdispater,項目名稱:clikit,代碼行數:15,代碼來源:string.py

示例14: validate_hostname

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def validate_hostname(hostname):
    if len(hostname) > 255:
        raise Exception("Hostname {} is longer than 255 characters".format(hostname))
    if hostname[-1] == ".":
        hostname = hostname[:-1]
    allowed = re.compile(r"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
    if not all(allowed.match(x) for x in hostname.split(".")):
        raise Exception("Hostname {} is not RFC 1123 compliant".format(hostname)) 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:10,代碼來源:__init__.py

示例15: natural_sort

# 需要導入模塊: import re [as 別名]
# 或者: from re import split [as 別名]
def natural_sort(i):
    return sorted(i, key=lambda s: [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]) 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:4,代碼來源:__init__.py


注:本文中的re.split方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。