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


Python re.re_split函数代码示例

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


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

示例1: system_info

def system_info():
    viewer_log_file = "/tmp/screenly_viewer.log"
    if path.exists(viewer_log_file):
        viewlog = check_output(["tail", "-n", "20", viewer_log_file]).split("\n")
    else:
        viewlog = ["(no viewer log present -- is only the screenly server running?)\n"]

    # Get load average from last 15 minutes and round to two digits.
    loadavg = round(getloadavg()[2], 2)

    try:
        run_tvservice = check_output(["tvservice", "-s"])
        display_info = re_split("\||,", run_tvservice.strip("state:"))
    except:
        display_info = False

    # Calculate disk space
    slash = statvfs("/")
    free_space = size(slash.f_bavail * slash.f_frsize)

    # Get uptime
    uptime_in_seconds = uptime()
    system_uptime = timedelta(seconds=uptime_in_seconds)

    return template(
        "system_info",
        viewlog=viewlog,
        loadavg=loadavg,
        free_space=free_space,
        uptime=system_uptime,
        display_info=display_info,
    )
开发者ID:robburrows,项目名称:screenly-ose,代码行数:32,代码来源:server.py

示例2: system_info

def system_info():
    viewer_log_file = '/tmp/sync_viewer.log'
    if path.exists(viewer_log_file):
        viewlog = check_output(['tail', '-n', '20', viewer_log_file]).split('\n')
    else:
        viewlog = ["(no viewer log present -- is only the sync server running?)\n"]

    # Get load average from last 15 minutes and round to two digits.
    loadavg = round(getloadavg()[2], 2)

    try:
        run_tvservice = check_output(['tvservice', '-s'])
        display_info = re_split('\||,', run_tvservice.strip('state:'))
    except:
        display_info = False

    # Calculate disk space
    slash = statvfs("/")
    free_space = size(slash.f_bavail * slash.f_frsize)

    # Get uptime
    uptime_in_seconds = uptime()
    system_uptime = timedelta(seconds=uptime_in_seconds)

    return template('system_info', viewlog=viewlog, loadavg=loadavg, free_space=free_space, uptime=system_uptime, display_info=display_info)
开发者ID:Geo-Joy,项目名称:sync-pi-ose,代码行数:25,代码来源:server.py

示例3: google_tts

def google_tts(text, tl='en', ip_addr=None):
    """
    this function is adapted from https://github.com/hungtruong/Google-Translate-TTS, thanks @hungtruong.
    """
	#process text into chunks
    text = text.replace('\n','')
    text_list = re_split('(\,|\.)', text)
    combined_text = []
    for idx, val in enumerate(text_list):
        if idx % 2 == 0:
            combined_text.append(val)
        else:
            joined_text = ''.join((combined_text.pop(),val))
            if len(joined_text) < 100:
                combined_text.append(joined_text)
            else:
                subparts = re_split('( )', joined_text)
                temp_string = ""
                temp_array = []
                for part in subparts:
                    temp_string = temp_string + part
                    if len(temp_string) > 80:
                        temp_array.append(temp_string)
                        temp_string = ""
                #append final part
                temp_array.append(temp_string)
                combined_text.extend(temp_array)
    #download chunks and write them to the output file
    f = NamedTemporaryFile(delete=False)
    host = ip_addr if ip_addr else "translate.google.com"
    headers = {"Host":"translate.google.com",
      "Referer":"http://www.gstatic.com/translate/sound_player2.swf",
      "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36"}
    for idx, val in enumerate(combined_text):
        mp3url = "http://%s/translate_tts?tl=%s&q=%s&total=%s&idx=%s" % (host, tl, quote(val), len(combined_text), idx)
        req = Request(mp3url, headers=headers)
        if len(val) > 0:
            try:
                response = urlopen(req)
                f.write(response.read())
            except HTTPError as e:
                pass
    f.close()
    system('afplay {0}'.format(f.name))
    unlink(f.name)
开发者ID:truebit,项目名称:PopClip-Extensions,代码行数:45,代码来源:bettertranslate.py

示例4: archive

 def archive(self):
     factoids = re_split(r'( or |\|)', self.info)[::2]
     formatted_info = "\n\n{} recorded on {} that {} is:\n* ".format(self.controller.config.get('server', 'nick'), datetime.today().date(), self.waiting) + "\n* ".join(factoids)
     try:
         page_url = self.append_page(formatted_info)
         self.controller.client.reply(self.requester[1], self.requester[0], "Done! {} -- I didn't delete the bot entry, just to be safe; please make sure I copied everything right, then do so.".format(page_url))
     except ResourceNotFoundError:
         self.controller.client.reply(self.requester[1], self.requester[0], "Sorry, that wiki page doesn't exist yet.")
     self.clear()
开发者ID:relsqui,项目名称:archivebot,代码行数:9,代码来源:kitnarchive.py

示例5: findWords

    def findWords(self, string):
        from re import compile as re_compile, split as re_split

        pattern = re_compile("\b?\w+\b")
        matches = re_split(pattern, string)
        if matches:
            return matches[0].split(" ")
        else:
            raise ValueError("%s did not have any recognizable single words" + " in the filename" % string)
开发者ID:uchicago-library,项目名称:uchicago-ldr-sips,代码行数:9,代码来源:LDRFileTree.py

示例6: get_features

 def get_features(self, source):
     """
     Feature extraction from text. The point where you can customize features.
     source - opened file
     return feature set, iterable object
     """
     words = []
     for line in source:
         if self.kind_of_partition == 'word':
             words.extend([word
                           for word in re_split('[\s,.:;!?<>+="()%\-0-9d]', line.decode("utf-8").lower().encode("utf-8"))
                           if word and (not self.est_words or word in self.est_words)
                           and word not in self.stopwords])
                           # not is_bad(word.decode("utf-8"))])
         elif self.kind_of_partition == 'ngram':
             for word in re_split('[\s,.:;!?<>+="()%\-]', line.decode("utf-8").lower().encode("utf-8")):
                 if word and word not in self.stopwords and word not in self.stopwords:
                     words.extend(re_findall('.{1,%d}' % self.ngram, word))
     return words
开发者ID:Ne88ie,项目名称:CSC_2014,代码行数:19,代码来源:classifier.py

示例7: convertHHMMtoSec

def convertHHMMtoSec(hhmm):
    vals = re_split(":", hhmm)
    if len(vals) == 2:
        h, m = vals[0], vals[1]
        s = 0
    elif len(vals) == 3:
        h, m, s = vals[0], vals[1], vals[2]
    else:
        raise Exception("not well formatted time string")
    return float(timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
开发者ID:zimmerst,项目名称:DmpWorkflow,代码行数:10,代码来源:tools.py

示例8: linebreaksbrpre

def linebreaksbrpre(str):
  # pre부분만 빼고...전부 바꿔주자.
  splited = re_split('</pre>',str)
  # 맨 마지막꺼 빼고 앞부분은 전부 <pre가 있는거렷다.
  lastStr = splited.pop()
  ret = []
  for splited_str in splited:
    # 여기서 앞부분것들만 pre에 적용을 안 받는 녀석들이다.
    pre_splited = re_split('<pre',splited_str)
    ret.append(linebreaksbr(pre_splited[0]))
    ret.append("<pre")
    if (len(pre_splited) > 1):
      split_content = pre_splited[1].split('>', 1)
    ret.append(split_content[0])  # <pre ~~~> 뒷부분
    ret.append('>')
    if (len(split_content) > 1):
      ret.append(split_content[1].replace("<", "&lt;").replace('>', '&gt;'))  # <pre>~~~</pre> 내용
    ret.append("</pre>")
  ret.append(linebreaksbr(lastStr))
  return "".join(ret)
开发者ID:limsungkee,项目名称:yonseics,代码行数:20,代码来源:linebreaksbrpre.py

示例9: deserialize

    def deserialize(cls, string):
        result = {}
        for line in string.split("\n"):
            if line == '':
                continue

            _, key, value, _ = re_split("(?<=[^\\\])/", line)
            key = cls._escape_filename(key.strip(), True)
            value = cls._escape_filename(value.strip(), True)
            result[key] = value
        return result
开发者ID:peritus,项目名称:hashedassets,代码行数:11,代码来源:serializer.py

示例10: parse_line

 def parse_line(cls, line, create=True, **kwargs):
     tags = []
     for possible_tag in re_split('[,\s]+', line):
         tag = cls.get_by_name(
             possible_tag.lower(),
             create=create,
             **kwargs
         )
         if tag:
             tags.append(tag)
     return tags
开发者ID:Zauberstuhl,项目名称:pyaspora,代码行数:11,代码来源:models.py

示例11: _format

def _format(storage, string, pattern, padding):
    # Split content by lines and leading indentation
    linedata = iter(re_split(pattern, string))
    # Add first line to content
    storage.append(_LONG*' ' + next(linedata))
    # For each padding and content of line
    for space, data in zip(linedata, linedata):
        # Normalise leading padding if necessary
        indent = len(space) - padding
        storage.append((_LONG + (indent if indent > 0 else 0))*' ' + data)
    # If last line of comment has no new line at the end, append one
    if not storage[-1].endswith('\n'):
        storage[-1] += '\n'
开发者ID:matt-hayden,项目名称:cutils,代码行数:13,代码来源:ccom.py

示例12: read

 def read(self, delay=0):
     """
     read one command from SNAP system
     """
     sleep(delay)
     stderr.write("___________READ___________\n")
     line = self.process.stdout.readline()
     read = line
     while read != "X\n":
         stderr.write("INFO:" + read)
         line = read
         read = self.process.stdout.readline()
     # stderr.write("HERE:" + str(re_split(r"[\n ]+",line)[0]) + "/end")
     return re_split(r"[\n ]+", line)[0]
开发者ID:danwangkoala,项目名称:vera_chil,代码行数:14,代码来源:SnapComm.py

示例13: checksum

def checksum(sentence):
    """ Calculate the checksum for a sentence (e.g. NMEA string). """

    result = {'checksum':None}
    # Remove any newlines
    if re_search("\n$", sentence):
        sentence = sentence[:-1]

    nmeadata,cksum = re_split('\*', sentence)

    calc_cksum = 0
    for s in nmeadata:
        calc_cksum ^= ord(s)

    # Return the nmeadata, the checksum from sentence, and the calculated checksum
    result['checksum'] = hex(calc_cksum)[2:].upper()
    return result
开发者ID:jslatte,项目名称:tartaros,代码行数:17,代码来源:utility.py

示例14: handle

 def handle(self):
     self._logger.debug('handle')
     request = self.request.recv(MAX_REQUEST_SIZE)        
     if request:
         self._logger.debug('request of size %d (%s)'%(len(request), b2a.hexlify(request[:8])))
         args = re_split(self.string_separator, request[1:]) #TODO-3 ??? figure out way to use self.string_separator(should work now)
         command = unpack('>b', request[0])[0]
         method = self.server._command_set.get(command)
         if method:
             response = self.server._command_set[command](*args)
         else:
             self._logger.error('no such command word %d!'%command)
             response = pack('>b', -1)
     else:
         self._logger.error('null packet received!')
         response = pack('>b', -2)
     self.request.send(response)
开发者ID:sma-wideband,项目名称:phringes,代码行数:17,代码来源:hardware.py

示例15: readHitsTBL

    def readHitsTBL(self):
        """Look for the next hit in tblout format, package and return"""
        """
We expect line to look like:
NODE_110054_length_1926_cov_24.692627_41_3 -          Ribosomal_S9         PF00380.14   5.9e-48  158.7   0.0   6.7e-48  158.5   0.0   1.0   1   0   0   1   1   1   1 # 1370 # 1756 # 1 # ID=41_3;partial=00;start_type=ATG;rbs_motif=None;rbs_spacer=None
        """
        while (1):
            line = self.handle.readline().rstrip()
            try:
                if line[0] != '#' and len(line) != 0:
                    dMatch = re_split( r'\s+', line.rstrip() )
                    if len(dMatch) < 19:
                        raise FormatError( "Something is wrong with this line:\n%s" % (line) )
                    refined_match = dMatch[0:18] + [" ".join([str(i) for i in dMatch[18:]])]
                    return HmmerHitTBL(refined_match)
            except IndexError:
                return {}
开发者ID:kulkarnik,项目名称:SimpleHMMER,代码行数:17,代码来源:simplehmmer.py


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