コード例 #1
0
ファイル: prittag.py プロジェクト: n1m3/prittag
def strip_string(string):
    if len(string.splitlines()) > 1:
        new_string = '\n'.join([i.strip() for i in string.splitlines()])
        new_string = new_string[1:]  # remove \n at the beginning of the string
        if string[len(string) - 1] != '\n':
            new_string = new_string[:len(new_string) - 1]
            #remove \n at the end of the string if wasn't present before
        return new_string

    else:
        return string.strip()
コード例 #2
0
ファイル: prittag.py プロジェクト: ltsavar/prittag
def strip_string(string):
    if len(string.splitlines()) > 1:
        new_string = '\n'.join([i.strip() for i in string.splitlines()])
        new_string = new_string[1:]  # remove \n at the beginning of the string
        if string[len(string) - 1] != '\n':
            new_string = new_string[:len(new_string) - 1]
            #remove \n at the end of the string if wasn't present before
        return new_string

    else:
        return string.strip()
コード例 #3
0
ファイル: client.py プロジェクト: fg123/terminal-messenger
    def update_chat_window(self):
        self.chat_window.clear()
        self.chat_window.box()
        # Subtract two for the borders
        max_rows = self.chat_height - 2
        row = 1
        actual_lines = []
        messages = self.get_current_messages()
        for string, attr in messages[-max_rows:]:
            lines = string.splitlines()
            if not lines:
                # We don't want to ignore empty lines (for new line purposes)
                actual_lines.append(('', attr))
            else:
                for line in lines:
                    parts = textwrap.wrap(line, self.chat_width - 2)
                    for part in parts:
                        actual_lines.append((part, attr))

        for line, attr in actual_lines[-max_rows:]:
            try:
                self.chat_window.addstr(row, 1, line, attr)
                row += 1
            except:
                pass
        self.chat_window.refresh()
コード例 #4
0
ファイル: resource.py プロジェクト: nr-plugins/c4ddev
def parse_symbols_string(string):
  # Remove all comments from the source.
  string = ' '.join(line.split('//')[0] for line in string.splitlines())
  string = ' '.join(re.split(r'\/\*.*\*\/', string))

  # Extract all enumeration declarations from the source.
  enumerations = [
    text.split('{')[1].split('}')[0]
    for text in re.split(r'\benum\b', string)[1:]
  ]

  # Load the symbols.
  symbols = {}
  masked_symbols = []
  for enum in enumerations:
    last_value = -1
    for name in enum.split(','):
      if '=' in name:
        name, value = name.split('=')
        value = int(value)
      else:
        value = last_value + 1

      name = name.strip()
      if name:
        if name in symbols and symbols[name] != value:
          masked_symbols.append((name, symbols[name]))
        last_value = value
        if not name.startswith('_'):
          symbols[name] = value

  return (symbols, masked_symbols)
コード例 #5
0
def readClustal(string, alphabet):
    """ Read a ClustalW2 alignment in the given string and return as an
    Alignment object. """
    seqs = {}  # sequence data
    for line in string.splitlines():
        if line.startswith('CLUSTAL') or line.startswith('STOCKHOLM') \
           or line.startswith('#'):
            continue
        if len(line.strip()) == 0:
            continue
        if line[0] == ' ' or '*' in line or ':' in line:
            continue
        sections = line.split()
        name, seqstr = sections[0:2]
        index = name.find('/')
        if index >= 0:
            name = name[0:index]
        if name in seqs:
            seqs[name] += seqstr
        else:
            seqs[name] = seqstr
    sequences = []
    for name, seqstr in list(seqs.items()):
        sequences.append(Sequence(seqstr, alphabet, name, gappy=True))
    return Alignment(sequences)
コード例 #6
0
    def _render_diff_block(self, contents, sub, current_block, before,
                           is_diff):
        """Renders one side of a diff block (either `before` or `after`)."""

        rendered = []

        for diff in current_block:
            start, end = diff.span
            if isinstance(diff, substitution.DiffSpan):
                style = colorama.Fore.RED if before else colorama.Fore.GREEN
                style += colorama.Style.BRIGHT
                string = contents[start:end] if before else diff.after
            else:
                style = self._style_for(sub, diff)
                # TODO: How to colorize a diff is actually really difficult
                # to decide. For example, should we make the match itself non-dim? red
                # but not bright?
                # It may be that we want to add more configuration hooks and metadata
                # that gets injected here.
                if is_diff:
                    style += colorama.Style.DIM
                string = contents[start:end]

            # Style the whole string, but break around \n so that we can add/remove
            # formatting at line boundaries.
            for line in string.splitlines(True):
                tail = ''
                if line.endswith('\n'):
                    tail = '\n'
                    line = line[:-1]
                rendered.append(self._style(style, line) + tail)

        return ''.join(rendered)
コード例 #7
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def dickfilm():
   if random.randint(1000,2000) == 1337:
      return "The twilight saga"
      
   f = open('film.txt', 'r+')
   string = ''
   string2 = ''
   for linje in f:
      if (' ' in linje):
         string+=linje
   filmer = string.splitlines()
   string = filmer[random.randint(0, len(filmer)-1)]
   words = string.split(' ')
   tall = random.randint(0, len(words)-1)
   if (words[tall] == 'The' or words[tall] == 'the'):
      tall=tall+1
   if (tall == 0 or words[tall][0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
      if (words[tall][-1]=='s'):
         words[tall] = 'Dicks'
      else:
         words[tall] = 'Dick'
   else:
      if (words[tall][-1]=='s'):
         words[tall] = 'dicks'
      else:
         words[tall] = 'dick'
   for i in range(0, len(words)):
      string2+= words[i]
      if (i < len(words)-1):
         string2 += ' '
   return "\""+string2+"\""
コード例 #8
0
def innerTrim(string):
    if isinstance(string, (unicode, str)):
        # remove tab and white space
        string = re.sub(TABSSPACE, ' ', string)
        string = ''.join(string.splitlines())
        return string.strip()
    return ''
コード例 #9
0
ファイル: text.py プロジェクト: SalesLoft/python-goose
def innerTrim(string):
    if isinstance(string, (unicode, str)):
        # remove tab and white space
        string = re.sub(TABSSPACE, ' ',string)
        string = ''.join(string.splitlines())
        return string.strip()
    return ''
コード例 #10
0
def add_indent(level, string):
    lines = string.splitlines()
    indent = ''
    for i in range(level):
        indent = indent + '\t'

    return ''.join(['\n' + indent + line for line in lines])
コード例 #11
0
ファイル: sequence.py プロジェクト: jacekrad/biol3014
def readClustal(string, alphabet):
    """ Read a ClustalW2 alignment in the given string and return as an
    Alignment object. """
    seqs = {} # sequence data
    for line in string.splitlines():
        if line.startswith('CLUSTAL') or line.startswith('STOCKHOLM') \
           or line.startswith('#'):
            continue
        if len(line.strip()) == 0:
            continue
        if line[0] == ' ' or '*' in line or ':' in line:
            continue
        sections = line.split()
        name, seqstr = sections[0:2]
        index = name.find('/')
        if index >= 0:
            name = name[0:index] 
        if seqs.has_key(name):
            seqs[name] += seqstr
        else:
            seqs[name] = seqstr
    sequences = []
    for name, seqstr in seqs.items():
        sequences.append(Sequence(seqstr, alphabet, name, gappy = True))
    return Alignment(sequences)
コード例 #12
0
def dickfilm():
    if random.randint(1000, 2000) == 1337:
        return "The twilight saga"

    f = open('film.txt', 'r+')
    string = ''
    string2 = ''
    for linje in f:
        if (' ' in linje):
            string += linje
    filmer = string.splitlines()
    string = filmer[random.randint(0, len(filmer) - 1)]
    words = string.split(' ')
    tall = random.randint(0, len(words) - 1)
    if (words[tall] == 'The' or words[tall] == 'the'):
        tall = tall + 1
    if (tall == 0 or words[tall][0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
        if (words[tall][-1] == 's'):
            words[tall] = 'Dicks'
        else:
            words[tall] = 'Dick'
    else:
        if (words[tall][-1] == 's'):
            words[tall] = 'dicks'
        else:
            words[tall] = 'dick'
    for i in range(0, len(words)):
        string2 += words[i]
        if (i < len(words) - 1):
            string2 += ' '
    return "\"" + string2 + "\""
コード例 #13
0
ファイル: parser.py プロジェクト: knangia/syntribos
    def create_request(cls, string, endpoint, meta_vars=None):
        """Parse the HTTP request template into its components

        :param str string: HTTP request template
        :param str endpoint: URL of the target to be tested
        :param dict meta_vars: Default None, dict parsed from meta.json
        :rtype: :class:`syntribos.clients.http.parser.RequestObject`
        :returns: RequestObject with method, url, params, etc. for use by
                  runner
        """
        if meta_vars:
            cls.meta_vars = meta_vars
        string = cls.call_external_functions(string)
        action_field = str(uuid.uuid4()).replace("-", "")
        string = string.replace(cls.ACTION_FIELD, action_field)
        lines = string.splitlines()
        for index, line in enumerate(lines):
            if line == "":
                break
        if lines[index] != "":
            index = index + 1
        method, url, params, version = cls._parse_url_line(lines[0], endpoint)
        headers = cls._parse_headers(lines[1:index])
        data = cls._parse_data(lines[index + 1:])
        return RequestObject(
            method=method, url=url, headers=headers, params=params, data=data,
            action_field=action_field)
コード例 #14
0
ファイル: parser.py プロジェクト: voidp34r/syntribos
    def create_request(cls, string, endpoint, meta_vars=None):
        """Parse the HTTP request template into its components

        :param str string: HTTP request template
        :param str endpoint: URL of the target to be tested
        :param dict meta_vars: Default None, dict parsed from meta.json
        :rtype: :class:`syntribos.clients.http.parser.RequestObject`
        :returns: RequestObject with method, url, params, etc. for use by
                  runner
        """
        if meta_vars:
            cls.meta_vars = meta_vars
        string = cls.call_external_functions(string)
        action_field = str(uuid.uuid4()).replace("-", "")
        string = string.replace(cls.ACTION_FIELD, action_field)
        lines = string.splitlines()
        for index, line in enumerate(lines):
            if line == "":
                break
        if lines[index] != "":
            index = index + 1
        method, url, params, version = cls._parse_url_line(lines[0], endpoint)
        headers = cls._parse_headers(lines[1:index])
        data = cls._parse_data(lines[index + 1:])
        return RequestObject(method=method,
                             url=url,
                             headers=headers,
                             params=params,
                             data=data,
                             action_field=action_field)
コード例 #15
0
ファイル: resource.py プロジェクト: umar-ahmed/c4ddev
def parse_symbols_string(string):
  # Remove all comments from the source.
  string = ' '.join(line.split('//')[0] for line in string.splitlines())
  string = ' '.join(re.split(r'\/\*.*\*\/', string))

  # Extract all enumeration declarations from the source.
  enumerations = [
    text.split('{')[1].split('}')[0]
    for text in re.split(r'\benum\b', string)[1:]
  ]

  # Load the symbols.
  symbols = {}
  masked_symbols = []
  for enum in enumerations:
    last_value = -1
    for name in enum.split(','):
      if '=' in name:
        name, value = name.split('=')
        value = int(value)
      else:
        value = last_value + 1

      name = name.strip()
      if name:
        if name in symbols and symbols[name] != value:
          masked_symbols.append((name, symbols[name]))
        last_value = value
        if not name.startswith('_'):
          symbols[name] = value

  return (symbols, masked_symbols)
コード例 #16
0
def readFasta(string,
              alphabet=None,
              ignore=False,
              gappy=False,
              parse_defline=True):
    """ Read the given string as FASTA formatted data and return the list of
        sequences contained within it.
        If alphabet is specified, use it, if None (default) then guess it.
        If ignore is False, errors cause the method to fail.
        If ignore is True, errors will disregard sequence.
        If gappy is False (default), sequence cannot contain gaps,
        if True gaps are accepted and included in the resulting sequences.
        If parse_defline is False, the name will be set to everything before the first space, else parsing will be attempted."""
    seqlist = []  # list of sequences contained in the string
    seqname = None  # name of *current* sequence
    seqinfo = None
    seqdata = []  # sequence data for *current* sequence
    for line in string.splitlines():  # read every line
        if len(line) == 0:  # ignore empty lines
            continue
        if line[0] == '>':  # start of new sequence
            if seqname:  # check if we've got one current
                try:
                    current = Sequence(seqdata, alphabet, seqname, seqinfo,
                                       gappy)
                    seqlist.append(current)
                except RuntimeError as errmsg:
                    if not ignore:
                        raise RuntimeError(errmsg)
            # now collect data about the new sequence
            seqinfo = line[1:].split()  # skip first char
            if len(seqinfo) > 0:
                try:
                    if parse_defline:
                        parsed = parseDefline(seqinfo[0])
                        seqname = parsed[0]
                    else:
                        seqname = seqinfo[0]
                    seqinfo = line[1:]
                except IndexError as errmsg:
                    if not ignore:
                        raise RuntimeError(errmsg)
            else:
                seqname = ''
                seqinfo = ''
            seqdata = []
        else:  # we assume this is (more) data for current
            cleanline = line.split()
            for thisline in cleanline:
                seqdata.extend(tuple(thisline.strip('*')))
    # we're done reading the file, but the last sequence remains
    if seqname:
        try:
            lastseq = Sequence(seqdata, alphabet, seqname, seqinfo, gappy)
            seqlist.append(lastseq)
        except RuntimeError as errmsg:
            if not ignore:
                raise RuntimeError(errmsg)
    return seqlist
コード例 #17
0
def grabContent(string):
    string = string.splitlines()
    #for events
    frequency = "RRULE:FREQ=DAILY"
    time = "10"
    description = ""

    events = []

    titlearray = [
        "take", "daily", "bedtime", "every", "needed", "mouth", "hours",
        "capsule", "tablespoon", "days", "up to", "one"
    ]

    for i in string:
        print(i)
        i = re.sub(r'([^\s\w]|_)+', '', i)
        print(i, "/n")
        if any(word in i.lower() for word in titlearray):
            description += i
    twotime = ['twice']
    threetime = [
        'times',
        '3',
        'a day',
        "8",
    ]
    fourtime = ['6']
    night = ['night', 'bedtime']
    tendays = ['10']

    #TWO TIMES
    if any(word in description.lower() for word in twotime):
        events.append(getEvent(description, "08", frequency))
        events.append(getEvent(description, "20", frequency))
    #THREE TIMES
    elif any(word in description.lower() for word in threetime):
        events.append(getEvent(description, "08", frequency))
        events.append(getEvent(description, "14", frequency))
        events.append(getEvent(description, "20", frequency))
        if '10' in description.lower():
            frequency = "RRULE:FREQ=DAILY;COUNT=10"
    #FOUR TIMES
    elif any(word in description.lower() for word in fourtime):
        events.append(getEvent(description, "08", frequency))
        events.append(getEvent(description, "13", frequency))
        events.append(getEvent(description, "18", frequency))
        events.append(getEvent(description, "23", frequency))
    #AT NIGHT
    elif any(word in description.lower() for word in night):
        description = "TAKE ONE TABLET EVERY NIGHT AT BEDTIME"
        events.append(getEvent(description, "22", frequency))
    else:
        if len(description) < 10:
            description = "TAKE ONE TABLET"
        events.append(getEvent(description, "08", frequency))

    print(description)
    return events
コード例 #18
0
def get_grammar(string):
    grammar = set()
    for line in string.splitlines():
        head, symbols_str = line.split(' -> ')
        for symbols_str in symbols_str.split(' | '):
            symbols = tuple(symbols_str.split())
            grammar.add(Rule(head, symbols))
    return grammar
コード例 #19
0
def Body(string, cnt):
    count_words = {}
    lines = string.splitlines()
    for val in lines:
        if len(val):
            words = word_processing(val)
            inverted_index_step1(words, count_words)
    inverted_index_step2(count_words, body, cnt)
コード例 #20
0
def rhapsody():
    f = open('lyrics.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    lyrics = string.splitlines()
    for i in range(len(lyrics)):
        if (lyrics[i].lower() in message):
            irc.send('PRIVMSG ' + channel + ' :' + lyrics[i + 1] + '\r\n')
コード例 #21
0
def rune():
    f = open('rune.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    filmer = string.splitlines()
    nr = random.randint(0, len(filmer) - 1)
    string = filmer[nr]
    return string
コード例 #22
0
def film():
    f = open('film.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    filmer = string.splitlines()
    nr = random.randint(0, len(filmer) - 1)
    string = filmer[nr]
    return "\"" + string + "\""
コード例 #23
0
def sjekketriks():
    f = open('sjekketriks.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    sjekketriks = string.splitlines()
    tall = random.randint(0, len(sjekketriks) - 1)
    string = sjekketriks[tall]
    return string
コード例 #24
0
def youtube():
    f = open('youtube.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    reply = string.splitlines()
    tall = random.randint(0, len(reply) - 1)
    string = reply[tall]
    return string
コード例 #25
0
    def __init__(self, scenario, filename, string, language):
        self.file = fs.relpath(filename)
        self.line = None

        for pline, part in enumerate(string.splitlines()):
            part = part.strip()
            if re.match(u"%s: " % language.scenario_separator + re.escape(scenario.name), part):
                self.line = pline + 1
                break
コード例 #26
0
ファイル: pyorc_prototype.py プロジェクト: jacobjoaquin/csd
def strip_lines(string):
    '''Strips each individual line in a string.'''

    s = []

    for line in string.splitlines():
        s.append(line.strip())
        
    return '\n'.join(s)
コード例 #27
0
def strip_lines(string):
    '''Strips each individual line in a string.'''

    s = []

    for line in string.splitlines():
        s.append(line.strip())

    return '\n'.join(s)
コード例 #28
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def rune():
   f = open('rune.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   filmer = string.splitlines()
   nr = random.randint(0, len(filmer)-1)
   string = filmer[nr]
   return string
コード例 #29
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def youtube():
   f = open('youtube.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   reply = string.splitlines()
   tall = random.randint(0, len(reply)-1)
   string = reply[tall]
   return string
コード例 #30
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def sjekketriks():
   f = open('sjekketriks.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   sjekketriks = string.splitlines()
   tall = random.randint(0, len(sjekketriks)-1)
   string = sjekketriks[tall]
   return string
コード例 #31
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def film():
   f = open('film.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   filmer = string.splitlines()
   nr = random.randint(0, len(filmer)-1)
   string = filmer[nr]
   return "\""+string+"\""
コード例 #32
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def rhapsody():
   f = open('lyrics.txt', 'r+')
   string=''
   for linje in f:
    string+=linje
   lyrics = string.splitlines()
   for i in range(len(lyrics)):
      if (lyrics[i].lower() in message):
         irc.send ( 'PRIVMSG ' + channel + ' :'+lyrics[i+1]+'\r\n' )
コード例 #33
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def filmz():
   f = open('film.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   filmerz = string.splitlines()
   for i in range(0, len(filmerz)):
      if (filmerz[i].lower() in message):
         return True
   return False
コード例 #34
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def greet():
   f = open('greetings.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   greetings = string.splitlines()
   for i in range(0, len(greetings)):
      if (greetings[i] in message):
         return True
   return False
コード例 #35
0
 def admins():
     f = open('adminz.txt', 'r+')
     string = ''
     for linje in f:
         string += linje
     admin = string.splitlines()
     for i in range(0, len(admin)):
         if (admin[i].lower() == user.lower()):
             return True
     return False
コード例 #36
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def no():
   f = open('no.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   nei = string.splitlines()
   for i in range(0, len(nei)):
      if (nei[i] in message):
         return True
   return False
コード例 #37
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def filmene():
   f = open('film.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   film = string.splitlines()
   for i in range(0, len(film)):
      if (film[i] in message):
         return True
   return False
コード例 #38
0
ファイル: test_deb822.py プロジェクト: pombreda/python-debian
    def deb822_from_format_string(self, string, dict_=PARSED_PACKAGE, cls=deb822.Deb822):
        """Construct a Deb822 object by formatting string with % dict.
        
        Returns the formatted string, and a dict object containing only the
        keys that were used for the formatting."""

        dict_subset = DictSubset(dict_)
        string = string % dict_subset
        parsed = cls(string.splitlines())
        return parsed, dict_subset
コード例 #39
0
def meld():
    f = open('mld.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    mldd = string.splitlines()
    for i in range(0, len(mldd)):
        if (mldd[i] in message):
            return True
    return False
コード例 #40
0
def clean_newlines(string):
    """Strip newlines and any trailing/following whitespace; rejoin
    with a single space where the newlines were.
    
    Bug: This routine will completely butcher any whitespace-formatted
    text."""
    
    if not string: return ''
    lines = string.splitlines()
    return ' '.join( [line.strip() for line in lines] )
コード例 #41
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
 def admins():
    f = open('adminz.txt', 'r+')
    string = ''
    for linje in f:
       string+= linje
    admin = string.splitlines()
    for i in range(0, len(admin)):
       if (admin[i].lower() == user.lower()):
          return True
    return False
コード例 #42
0
def filmene():
    f = open('film.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    film = string.splitlines()
    for i in range(0, len(film)):
        if (film[i] in message):
            return True
    return False
コード例 #43
0
def greet():
    f = open('greetings.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    greetings = string.splitlines()
    for i in range(0, len(greetings)):
        if (greetings[i] in message):
            return True
    return False
コード例 #44
0
def yes():
    f = open('yes.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    ja = string.splitlines()
    for i in range(0, len(ja)):
        if (ja[i] in message):
            return True
    return False
コード例 #45
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def meld():
   f = open('mld.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   mldd = string.splitlines()
   for i in range(0, len(mldd)):
      if (mldd[i] in message):
         return True
   return False
コード例 #46
0
def no():
    f = open('no.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    nei = string.splitlines()
    for i in range(0, len(nei)):
        if (nei[i] in message):
            return True
    return False
コード例 #47
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def yes():
   f = open('yes.txt', 'r+')
   string = ''
   for linje in f:
      string+=linje
   ja = string.splitlines()
   for i in range(0, len(ja)):
      if (ja[i] in message):
         return True
   return False
コード例 #48
0
def filmz():
    f = open('film.txt', 'r+')
    string = ''
    for linje in f:
        string += linje
    filmerz = string.splitlines()
    for i in range(0, len(filmerz)):
        if (filmerz[i].lower() in message):
            return True
    return False
コード例 #49
0
ファイル: strings.py プロジェクト: DominikGuzei/lettuce
def get_stripped_lines(string, ignore_lines_starting_with=''):
    string = unicode(string)
    lines = [unicode(l.strip()) for l in string.splitlines()]
    if ignore_lines_starting_with:
        filter_func = lambda x: x and not x.startswith(ignore_lines_starting_with)
    else:
        filter_func = lambda x: x

    lines = filter(filter_func, lines)

    return lines
コード例 #50
0
def get_stripped_lines(string, ignore_lines_starting_with=''):
    string = unicode(string)
    lines = [unicode(l.strip()) for l in string.splitlines()]
    if ignore_lines_starting_with:
        filter_func = lambda x: x and not x.startswith(
            ignore_lines_starting_with)
    else:
        filter_func = lambda x: x

    lines = filter(filter_func, lines)

    return lines
コード例 #51
0
ファイル: stutter.py プロジェクト: kerkeslager/sandbox
def indent(string):
    assert isinstance(string, str)

    def indent_line(line):
        line = line.rstrip()

        if line == '':
            return line

        return ' ' * TAB_WIDTH + line

    return '\n'.join(indent_line(line) for line in string.splitlines())
コード例 #52
0
def filmReturn():
    f = open('film.txt', 'r+')
    thefilm = ''
    string = ''
    for linje in f:
        string += linje
    filmerz = string.splitlines()
    for i in range(0, len(filmerz)):
        if (filmerz[i].lower() in message.lower()):
            thefilm = filmerz[i].lower()
            return thefilm
    return ''
コード例 #53
0
ファイル: config.py プロジェクト: jimbolton/rose
def main():
    """Implement the "rose config" command."""
    opt_parser = RoseOptionParser()
    opt_parser.add_my_options("default", "files", "keys", "no_ignore")
    opts, args = opt_parser.parse_args()
    try:
        if opts.files:
            root_node = ConfigNode()
            for file in opts.files:
                if file == "-":
                    load(sys.stdin, root_node)
                    sys.stdin.close()
                else:
                    load(file, root_node)
        else:
            root_node = default_node()
    except SyntaxError as e:
        sys.exit(repr(e))
    if opts.quietness:
        if root_node.get(args, opts.no_ignore) is None:
            sys.exit(1)
    elif opts.keys_mode:
        try:
            keys = root_node.get(args, opts.no_ignore).value.keys()
        except:
            sys.exit(1)
        keys.sort()
        for key in keys:
            print key
    elif len(args) == 0:
        dump(root_node)
    else:
        node = root_node.get(args, opts.no_ignore)
        if node is not None and isinstance(node.value, dict):
            keys = node.value.keys()
            keys.sort()
            for key in keys:
                node_of_key = node.get([key], opts.no_ignore)
                value = node_of_key.value
                state = node_of_key.state
                string = "%s%s=%s" % (state, key, value)
                lines = string.splitlines()
                print lines[0]
                i_equal = len(state + key) + 1
                for line in lines[1:]:
                    print " " * i_equal + line
        else:
            if node is None:
                if opts.default is None:
                    sys.exit(1)
                print opts.default
            else:
                print node.value
コード例 #54
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def filmReturn():
   f = open('film.txt', 'r+')
   thefilm = ''
   string = ''
   for linje in f:
      string+=linje
   filmerz = string.splitlines()
   for i in range(0, len(filmerz)):
      if (filmerz[i].lower() in message.lower()):
         thefilm = filmerz[i].lower()
         return thefilm
   return ''
コード例 #55
0
def remove_empty_linesc(string, verbose=False):
    string = string.splitlines()

    new_string = []
    for s in string:
        if s != "":
            new_string.append(s)

    if verbose == True:
        print(new_string[2:][:10])

    return new_string[0], new_string[1], new_string[2:]
コード例 #56
0
    def deb822_from_format_string(self,
                                  string,
                                  dict_=PARSED_PACKAGE,
                                  cls=deb822.Deb822):
        """Construct a Deb822 object by formatting string with % dict.
        
        Returns the formatted string, and a dict object containing only the
        keys that were used for the formatting."""

        dict_subset = DictSubset(dict_)
        string = string % dict_subset
        parsed = cls(string.splitlines())
        return parsed, dict_subset
コード例 #57
0
def get_indent_level(string):
    '''Returns the indentation of first line of string
    '''
    lines = string.splitlines()
    lineno = 0
    line = lines[lineno]
    indent = 0
    total_lines = len(lines)
    while line < total_lines and indent == 0:
        indent = len(line) - len(line.lstrip())
        line = lines[lineno]
        line += 1

    return indent
コード例 #58
0
ファイル: conf.py プロジェクト: Annatara/nimbus
    def __init__(self, string):

        """Instantiate class with string.

        Required arguments:

        * string -- String to treat as file-like object, can contain newlines

        """

        if string is None:
            raise InvalidConfig("config file (string) can not be None")

        self.lines = string.splitlines(True)
        self.gen = self.genline()
コード例 #59
0
ファイル: bot.py プロジェクト: sigvef/fyllebot
def getAnswers(filen = 'answers.txt'):
   f = open(filen, 'r+')
   string = ''
   for linje in f:
      string+=linje
   tempList = string.splitlines()
   for i in range(0, len(tempList)):
      if (('[' in tempList[i]) and (']' in tempList[i]) and (', ' in tempList[i])):
         tempList[i] = tempList[i][1:-1]
         tempList[i] = tempList[i].lower().split(', ')
      else:
         placeholder = []
         placeholder.append(tempList[i].lower())
         tempList[i] = placeholder
   return tempList