def _find_fstring_string(endpats, fstring_stack, line, lnum, pos):
    tos = fstring_stack[-1]
    allow_multiline = tos.allow_multiline()
    if allow_multiline:
        match = fstring_string_multi_line.match(line, pos)
    else:
        match = fstring_string_single_line.match(line, pos)
    if match is None:
        return tos.previous_lines, pos

    if not tos.previous_lines:
        tos.last_string_start_pos = (lnum, pos)

    string = match.group(0)
    for fstring_stack_node in fstring_stack:
        end_match = endpats[fstring_stack_node.quote].match(string)
        if end_match is not None:
            string = end_match.group(0)[:-len(fstring_stack_node.quote)]

    new_pos = pos
    new_pos += len(string)
    if allow_multiline and (string.endswith('\n') or string.endswith('\r')):
        tos.previous_lines += string
        string = ''
    else:
        string = tos.previous_lines + string

    return string, new_pos
Ejemplo n.º 2
0
    def is_multiline_end(self, string):
        start_quote = False
        end_quote = False

        if string.startswith("\"") and not string.startswith("\"\"\""):
            start_quote = True
        if string.endswith("\"") and not string.endswith("\"\"\""):
            end_quote = True

        # line that only contains a quote
        if len(string) == 1 and (start_quote or end_quote):
            return True

        return end_quote and (end_quote and not start_quote)
Ejemplo n.º 3
0
    def is_multiline_start(self, string):
        start_quote = False
        end_quote = False

        if string.startswith('"') and not string.startswith('"""'):
            start_quote = True
        if string.endswith('"') and not string.endswith('"""'):
            end_quote = True

        # line that only contains a quote
        if len(string.strip()) == 1 and (start_quote or end_quote):
            return True

        return start_quote and (start_quote and not end_quote)
Ejemplo n.º 4
0
def string_remove_quotes(string):
    if type(string) not in (str, unicode):
        return string

    for char in ('"', "'"):
        if string.startswith(char) and string.endswith(char):
            return string[1:-1]
Ejemplo n.º 5
0
def rtrim(string, suffix):
    ''' Trim all suffixes from string. '''

    length = len(suffix)
    while string.endswith(suffix):
        string = string[:-length]
    return string
Ejemplo n.º 6
0
 def getCryptUrl(self, string):
     if string.find("?") < 0:
         string += "?"
     if not string.endswith("?"):
         string += "&"
     string += "cyt=1"
     return string
Ejemplo n.º 7
0
def _find_fstring_string(fstring_stack, line, lnum, pos):
    tos = fstring_stack[-1]
    if tos.is_in_expr():
        return '', pos
    else:
        new_pos = pos
        allow_multiline = tos.allow_multiline()
        if allow_multiline:
            match = fstring_string_multi_line.match(line, pos)
        else:
            match = fstring_string_single_line.match(line, pos)
        if match is None:
            string = tos.previous_lines
        else:
            if not tos.previous_lines:
                tos.last_string_start_pos = (lnum, pos)

            string = match.group(0)
            for fstring_stack_node in fstring_stack:
                try:
                    string = string[:string.index(fstring_stack_node.quote)]
                except ValueError:
                    pass  # The string was not found.

            new_pos += len(string)
            if allow_multiline and string.endswith('\n'):
                tos.previous_lines += string
                string = ''
            else:
                string = tos.previous_lines + string

        return string, new_pos
Ejemplo n.º 8
0
def remove_punctuation(word_list):

    for each_word in word_list:
        print type(each_word)

        if string.endswith("!"):
           word_list[each_word]=word_list[each_word].rstrip()
Ejemplo n.º 9
0
        def unQuote(string):
            """
            @param string:
            @type string:

            @return: The stripped string.
            @rtype: string
            """

            if string.startswith('"') and string.endswith('"'):
                string = string[1:-1]
                
            elif string.startswith("'") and string.endswith("'"):
                string = string[1:-1]

            return string
Ejemplo n.º 10
0
def getEmail(url):
	try:
		tokens=getHTML(url)
		contacts=[]
		for i in range(0,len(tokens)):
			if "@" in tokens[i]:
				string= str(tokens[i-1])
				if string[0].isalpha():
					string = string +str(tokens[i])
					string = string +str(tokens[i+1])
					endA=str(tokens[i+1])
					if endA.find(".")>=0:
						if is_in_arr(contacts,tokens[i])==False:
							if string.endswith(".")==False:
								contacts.append(string)
			if "at"==tokens[i]:
				if tokens[i-1]=="[" and tokens[i+1]=="]":
					string=str(tokens[i-2])+"@"+str(tokens[i+2])
					contacts.append(string)
			if len(tokens[i])==3:
				if tokens[i].isalpha==False:
					if (tokens[i+1].isalpha==False and len(tokens[i+1])==3) and (tokens[i+2].isalpha()==False and len(tokens[i+2])==3) and item not in contacts:
						string = str(tokens[i]) +str(tokens[i+1])+str(tokens[i+2])
						contacts.append("Email: "+string)
		new = deleteDuplicates(contacts)
		return new
	except:
		return "Error Occured"
Ejemplo n.º 11
0
def remove_punct(string):
    """Remove common punctuation marks."""
    if string.endswith('?'):
        string = string[:-1]
    return (string.replace(',', '')
            .replace('.', '')
            .replace(';', '')
            .replace('!', ''))
Ejemplo n.º 12
0
def remove_punct(string):

    if string.endswith('?'):
        string = string[:-1]
    return (string.replace(',', '')
            .replace(',', '')
            .replace(';', '')
            .replace('!', ''))
Ejemplo n.º 13
0
def chomp_string(string, postfix):
    """Chomps the given string off of the end of the given string, if
    the string is long enough and the character is there
    otherwise is doesn't touch the string"""
    if string.endswith(postfix):
        up_to_postfix = len(string) - len(postfix)
        string = string[:up_to_postfix]
    return string
def hey (string):
    if string.isspace() or string == "":
        return "Fine. Be that way!"
    elif string.isupper():
        return "Whoa, chill out!"
    elif string.endswith("?"):
        return "Sure."
    else:
        return "Whatever."
Ejemplo n.º 15
0
 def strip_trailing_slash(string):
     """
     If the string has a trailing '/', removes it
     :param string: string to check
     :return: string without a trailing '/'
     :rtype: string
     """
     if string.endswith('/'):
         return string[:-1]
     return string
Ejemplo n.º 16
0
    def zip(cls,
            string: Union[bytes, str],
            append_semicolon: bool = True) -> str:
        if isinstance(string, bytes):
            string = string.decode(errors="ignore")

        if append_semicolon and not string.endswith(";"):
            string += ";"

        return cls.encode_save(string, needs_xor=False)
Ejemplo n.º 17
0
def rstripSeparator(string):
    """Return a copy of *string* where whitespace at the end is removed. If after removing whitespace the
    string contains one of the separators from ``constants.SEPARATORS`` at its end, remove it together with
    additional whitespace."""
    string = string.rstrip()
    for sep in SEPARATORS:
        if string.endswith(sep):
            string = string[:-len(sep)]
            break
    return string.rstrip()
Ejemplo n.º 18
0
    def endswith(self, string, suffix, msg=None):
        """
        Asserts that first string ends with the second suffix

        :Args:
         - String to test
         - String suffix should be at the end of the string
         - Message that will be printed if it fails
        """

        assert string.endswith(suffix), msg
Ejemplo n.º 19
0
def dequote(string):
    """Takes string which may or may not be quoted and unquotes it.

    It only considers double quotes. This function does NOT consider
    parenthised lists to be quoted.
    """
    if string and string.startswith('"') and string.endswith('"'):
        string = string[1:-1]  # Strip off the surrounding quotes.
        string = string.replace('\\"', '"')
        string = string.replace('\\\\', '\\')
    return string
Ejemplo n.º 20
0
    def endswith(self, string, suffix, msg=None):
        """
        Asserts that first string ends with the second suffix

        :Args:
         - String to test
         - String suffix should be at the end of the string
         - Message that will be printed if it fails
        """

        assert string.endswith(suffix), msg
Ejemplo n.º 21
0
def dequote(string):
    """Takes string which may or may not be quoted and unquotes it.

    It only considers double quotes. This function does NOT consider
    parenthised lists to be quoted.
    """
    if string and string.startswith('"') and string.endswith('"'):
        string = string[1:-1]  # Strip off the surrounding quotes.
        string = string.replace('\\"', '"')
        string = string.replace('\\\\', '\\')
    return string
Ejemplo n.º 22
0
def remove_square_brackets(string):
    """
    Description:
        Removes square brackets "<>" from start and end of text
    Parameters:
        string (str): Text to be stripped
    Returns:
        string (str): Stripped string
    """
    string = string.strip()
    if string.startswith("<") and string.endswith(">"): return string[1:-1]
    return string
Ejemplo n.º 23
0
def remove_suffix(string, suffix):
    """
    This funtion removes the given suffix from a string, if the string
    does indeed end with the prefix; otherwise, it returns the string
    unmodified.
    """
    # Special case: if suffix is empty, string[:0] returns ''. So, test
    # for a non-empty suffix.
    if suffix and string.endswith(suffix):
        return string[:-len(suffix)]
    else:
        return string
Ejemplo n.º 24
0
def _innerize_selected_string(editor):
    '''Given that a string is selected, select only its contents.'''
    assert isinstance(editor, wingapi.CAPIEditor)
    selection_start, selection_end = editor.GetSelection()
    string = editor.GetDocument().GetCharRange(selection_start, selection_end)
    match = string_pattern.match(string)
    assert match
    delimiter = match.group('delimiter')
    prefix = match.group('prefix')
    fixed_start = selection_start + len(delimiter) + len(prefix)
    fixed_end = selection_end - len(delimiter) if string.endswith(delimiter) \
                                                             else selection_end
    editor.SetSelection(fixed_start, fixed_end)
Ejemplo n.º 25
0
def string_safe_shell(string):
    if string.startswith("'") and string.endswith("'"):
        return string
    else:
        return string_escape_char(
            string,
            str(
                '&();|\n'+  # Control operators
                '<>'+       # Redirection operators
                '!*?[]'+    # Shell patterns
                '$'         # Variables
            )
        )
Ejemplo n.º 26
0
def string_safe_shell(string):
    if string.startswith("'") and string.endswith("'"):
        return string
    else:
        return string_escape_char(
            string,
            str(
                '&();|\n'+  # Control operators
                '<>'+       # Redirection operators
                '!*?[]'+    # Shell patterns
                '$'         # Variables
            )
        )
Ejemplo n.º 27
0
def _find_fstring_string(endpats, fstring_stack, line, lnum, pos):
    tos = fstring_stack[-1]
    allow_multiline = tos.allow_multiline()
    if tos.is_in_format_spec():
        if allow_multiline:
            regex = fstring_format_spec_multi_line
        else:
            regex = fstring_format_spec_single_line
    else:
        if allow_multiline:
            regex = fstring_string_multi_line
        else:
            regex = fstring_string_single_line

    match = regex.match(line, pos)
    if match is None:
        return tos.previous_lines, pos

    if not tos.previous_lines:
        tos.last_string_start_pos = (lnum, pos)

    string = match.group(0)
    for fstring_stack_node in fstring_stack:
        end_match = endpats[fstring_stack_node.quote].match(string)
        if end_match is not None:
            string = end_match.group(0)[:-len(fstring_stack_node.quote)]

    new_pos = pos
    new_pos += len(string)
    # even if allow_multiline is False, we still need to check for trailing
    # newlines, because a single-line f-string can contain line continuations
    if string.endswith('\n') or string.endswith('\r'):
        tos.previous_lines += string
        string = ''
    else:
        string = tos.previous_lines + string

    return string, new_pos
Ejemplo n.º 28
0
def trim(string, xfix):
    ''' Trim all prefixes or suffixes of xfix from string. '''

    if is_string(string):
        string = string.encode()
    if is_string(xfix):
        xfix = xfix.encode()

    length = len(xfix)
    while string.startswith(xfix):
        string = string[length:]
    while string.endswith(xfix):
        string = string[:-length]
    return string
Ejemplo n.º 29
0
def trim(string, xfix):
    ''' Trim all prefixes or suffixes of xfix from string. '''

    if is_string(string):
        string = string.encode()
    if is_string(xfix):
        xfix = xfix.encode()

    length = len(xfix)
    while string.startswith(xfix):
        string = string[length:]
    while string.endswith(xfix):
        string = string[:-length]
    return string
Ejemplo n.º 30
0
def check_endswith(string, substring):
    """
    判断字符串是以什么结尾
    :param string:字符串
    :param substring:需要判断的结尾字符串
    :return:
    """
    # 检查你输入的是否是字符类型
    if isinstance(string, str):
        raise ValueError("参数不是字符串类型")
    # 判断字符串以什么结尾
    if string.endswith(substring):
        return True

    return False
Ejemplo n.º 31
0
def _find_fstring_string(endpats, fstring_stack, line, lnum, pos):
    tos = fstring_stack[-1]
    allow_multiline = tos.allow_multiline()
    if tos.is_in_format_spec():
        if allow_multiline:
            regex = fstring_format_spec_multi_line
        else:
            regex = fstring_format_spec_single_line
    else:
        if allow_multiline:
            regex = fstring_string_multi_line
        else:
            regex = fstring_string_single_line

    match = regex.match(line, pos)
    if match is None:
        return tos.previous_lines, pos

    if not tos.previous_lines:
        tos.last_string_start_pos = (lnum, pos)

    string = match.group(0)
    for fstring_stack_node in fstring_stack:
        end_match = endpats[fstring_stack_node.quote].match(string)
        if end_match is not None:
            string = end_match.group(0)[:-len(fstring_stack_node.quote)]

    new_pos = pos
    new_pos += len(string)
    if allow_multiline and (string.endswith('\n') or string.endswith('\r')):
        tos.previous_lines += string
        string = ''
    else:
        string = tos.previous_lines + string

    return string, new_pos
Ejemplo n.º 32
0
def chomp( string ):
    """
    Perl-Like Chomp; strips line endings and returns just the string

    >>> chomp( "test\\n" )
    'test'

    @param string: string to chomp
    @return: string without ending newline
    """
    if string.endswith( '\r\n' ):
        return string[:-2]
    if string[-1] == '\r' or string[-1] == '\n':
        return string[:-1]
    return string
Ejemplo n.º 33
0
def _innerize_selected_string(editor):
    '''Given that a string is selected, select only its contents.'''
    assert isinstance(editor, wingapi.CAPIEditor)
    selection_start, selection_end = editor.GetSelection()
    string = editor.GetDocument().GetCharRange(selection_start, selection_end)
    match = string_pattern.match(string)
    assert match
    delimiter = match.group('delimiter')
    prefix = match.group('prefix')
    fixed_start = selection_start + len(delimiter) + len(prefix)
    fixed_end = selection_end - len(delimiter) if string.endswith(delimiter) \
                                                             else selection_end
    editor.SetSelection(fixed_start, fixed_end)                               
        
    
Ejemplo n.º 34
0
def isvalid(string):
    # checks title start with wrong words
    for s in exe_start:
        if string.startswith(s):
            return False
    # checks title start with lower-case character
    if string[0:1].islower():
        return False
    # checks title end with wrong words
    for s in exe_ending:
        if string.endswith(s):
            return False
    # check title of wrong words
    for s in exe_title:
        if s == string:
            return False
    return True
def cleanName(name, ref_nb, ref_type):
    # ===============================================================================

    # define individual names by splitting them via 'and' separator
    # authors = name.lower().split(' and ')
    substrings = re.split(r"(?u)(?![\,\.,])\W+", name)
    substrings = [sub.lower() for sub in substrings]
    for i, sub in enumerate(substrings):
        if len(sub) > 1 and sub != "and" and "." not in sub:
            sub = sub[0].upper() + sub[1:]
        elif len(sub) > 1 and sub != "and" and "." in sub:
            sub = sub.upper()
            if not sub.endswith(".") and not sub.endswith(","):
                sub = sub + "."

        elif len(sub) == 1 and sub != "and":
            sub = sub.upper() + "."
        substrings[i] = sub

    author_list = substrings[0]
    for i, string in enumerate(substrings[1:]):
        if string.endswith(".") and substrings[i - 1].endswith("."):
            author_list += string
        else:
            author_list += " " + string

    # attach the {}'s and the comma, so we don't have to worry later on
    author_list = "{" + author_list + "}"

    # check for invalid format:
    invalidName = False
    # author_list is invalid if there is a missing parenthesis in the final string
    for par1, par2 in zip("({[", ")}]"):
        tt1 = author_list.split(par1)
        tt2 = author_list.split(par2)
        if len(tt1) != len(tt2):
            invalidName = True

    # return error if the item is invalid
    if invalidName == True:
        return author_list, (ref_nb, "invalid author list", author_list)

    # returns no error in all other cases
    else:
        return author_list, None
Ejemplo n.º 36
0
    def write_debug(self, string):
        """
        Engine writes a debugger message.
        """
        if self.AutoCompActive():
            self.AutoCompCancel()

        if string.endswith('\n') is False:
            string = string+'\n'

        #if we are prompting or reading user input add the string before the 
        #current prompt
        if (self.busy is False) or (self.reading is True) or (self.debugging is True):
            #add the line before the current prompt 
            pos = self.PositionFromLine(self._promptline)
            #check that we are not at the beginning
            if pos==0:
                self.SetCurrentPos(pos)
                self.AddText('\n')
                self._promptpos +=1
                self._promptline+=1

            #add the text before the newline
            self.SetCurrentPos(pos-1)
            self.AddText(string)

            #update the prompt position
            slen = len(string)
            slines = string.count('\n')
            self._promptline =self._promptline+slines
            self._promptpos = self._promptpos+slen
            self.SetAnchor(self.GetLength())
            self.SetCurrentPos(self.GetLength()) #set cursor to end position
            self.EnsureCaretVisible()
            return

        #just add the text at the end.
        self.SetAnchor(self.GetLength())
        self.SetCurrentPos(self.GetLength()) #set cursor to end position
        line,pos = self.GetCurLine()
        if line!='':    #add a newline before if necessary 
            self.AddText('\n')
        self.AddText(string)
        self.EnsureCaretVisible()
Ejemplo n.º 37
0
    def FormatSerie(self, string):

        # vire doubles espaces
        string = re.sub(' +', ' ', string)

        # vire espace a la fin
        if string.endswith(' '):
            string = string[:-1]

        # vire espace au debut
        if string.startswith(' '):
            string = string[1:]

        SXEX = ''
        m = re.search('(?i)(\wpisode ([0-9\.\-\_]+))', string, re.UNICODE)
        if m:
            # ok y a des episodes
            string = string.replace(m.group(1), '')
            # SXEX + '%02d' % int(m.group(2))
            SXEX = m.group(2)
            if len(SXEX) < 2:
                SXEX = '0' + SXEX
            SXEX = 'E' + SXEX

            # pr les saisons
            m = re.search('(?i)(s(?:aison )*([0-9]+))', string)
            if m:
                string = string.replace(m.group(1), '')
                SXEX = 'S' + '%02d' % int(m.group(2)) + SXEX
            string = string + ' ' + SXEX

        else:
            # pas d'episode mais y a t il des saisons ?
            m = re.search('(?i)(s(?:aison )*([0-9]+))(?:$| )', string)
            if m:
                string = string.replace(m.group(1), '')
                SXEX = 'S' + '%02d' % int(m.group(2))

                string = string + ' ' + SXEX

        # reconvertion utf-8
        return string.encode('utf-8')
Ejemplo n.º 38
0
def check_split(source, target, edits):
	s = []
	t = []
	# Collect the tokens
	for e in edits:
		s_tok = source[e[1]:e[2]].orth_.replace("'", "")
		t_tok = target[e[3]:e[4]].orth_.replace("'", "")
		if len(s_tok) >= 1: s.append(s_tok)
		if len(t_tok) >= 1: t.append(t_tok)
	
	if len(s) == len(t):
		return False
	elif len(s) == 1 and len(t) > 1:
		string = s[0]
		tokens = t
	elif len(t) == 1 and len(s) > 1:
		string = t[0]
		tokens = s
	else:
		return False
	# Check split
	if string.startswith(tokens[0]): # Matches beginning
		string = string[len(tokens[0]):]
		if string.endswith(tokens[-1]): # Matches end
			string = string[:-len(tokens[-1])]
			# Matches all tokens in the middle (in order)
			match = True
			for t in tokens[1:-1]:
				try:
					i = string.index(t)
					string = string[i+len(t):]
				except:
					# Token not found
					return False
			# All tokens found
			return True
	# Any other case is False
	return False
Ejemplo n.º 39
0
    async def summary(self, id):
        if id:
            soup = await self._get_soup(f'title/{id}/')

            # Get summary from the top
            candidates = (
                # Old website design
                soup.find(class_='summary_text'),
                # New website design
                soup.find(class_=re.compile(r'GenresAndPlot__TextContainerBreakpointXL.*')),
            )
            for tag in candidates:
                if tag:
                    string = ''.join(tag.stripped_strings).strip()
                    link_texts = ('See full summary»', 'Read all', 'Add a Plot»')
                    if all(not string.endswith(text) for text in link_texts):
                        return string

            # Get summary from the "Storyline" section (old website design)
            try:
                tag = soup.find(id='titleStoryLine').div.p.span
            except AttributeError:
                pass
            else:
                # Remove "Written by [Author]" signature
                return re.sub(r'\s*(?i:Written\s+by).*?$', '', ''.join(tag.strings)).strip()

            # Get summary from the "Storyline" section (new website design)
            try:
                tag = soup.find(class_=re.compile(r'^Storyline__StorylineWrapper.*')).div.div.div
            except AttributeError:
                pass
            else:
                # Remove "—[Author]" signature
                return re.sub(r'\s*—.*?$', '', ''.join(tag.strings)).strip()

        return ''
Ejemplo n.º 40
0
def delete_suffix(string, suffix):
    """ This function deletes the suffix string of a string. If
    the suffix does not exist, the string is returned unchanged.

    See https://stackoverflow.com/a/16891418

    Parameters
    ----------
    string : string
        The string that the suffix of which will be taken out.
    suffix : string
        The suffix.

    Returns
    -------
    base : string
        The string, without the suffix.

    """
    try:
        # This behavior is available in Python 3.9+. As such,
        # we have the fall back.
        string.removesuffix(suffix)
    except Exception:
        # The fall back solution.
        if string.endswith(suffix):
            string = string[:-len(suffix)]
        else:
            string = string
    finally:
        # Return, all done, naming convention.
        base = string
        return base

    # The code should not reach here.
    raise mono.BrokenLogicError
    return None
Ejemplo n.º 41
0
    def _parse_attr(self, string):
        """Parse a string in a way that can be easily interpreted as either
        a number or a string.

        :param string: string to be parsed
        :return: float if it can be converted, string otherwise
        """
        key_translator = {
            'pore_before': 'median_current$left',
            'pore_after': 'median_current$right',
            'strand_duration': 'duration',
            'median_before': 'median_current$left',
            'median': 'median_current',
            'range': 'range_current',
            'event_count': 'num_events',
        }

        if string in key_translator:
            string = key_translator[string]

        # If it is a number, return a number
        try:
            return float(string)
        except ValueError:
            pass

        # If it is literally a string to compare with, e.g. "'pore'", return the
        # string without the ''
        if string.startswith("'") and string.endswith("'"):
            return string.replace("'", "")
        if string.startswith('"') and string.endswith('"'):
            return string.replace('"', '')

        # If it's written in the new way 'median_current$0' or 'range_current$1'
        try:
            return Key(*string.split('$'))
        except TypeError:
            pass

        # If it is a subrule within a subrule, for example:
        #     median_current + 2 * range
        # return a Subrule
        # We need to be carefull to keep the priorities of operations, in
        # this case keeping the '*' and '/' till the end, so they are evaluated
        # first after recurrence
        for op in ['+', '-', '*', '/']:
            if op in string:
                try:
                    split = string.split(op)
                    split = [
                        key_translator[s] if s in key_translator else s
                        for s in split
                    ]
                    return SubRule('({}, {}, {})'.format(
                        split[0], op, split[1]))
                except SyntaxError:
                    pass

        # The last possible case is the keyword did not have a '$', which means
        # it refers to position 1 even if not explicitly stated, i.e. a good old
        # 'median_current' .
        return Key(string, 'centre')
Ejemplo n.º 42
0
 def non_utf_8_string_cleaner(self, string):
     if string.startswith("u'"):
         string = string[1:]
     if string.endswith("\\'"):
         string = string[:-3]
     return string.replace("\\\\", "\\").replace("'", "")
Ejemplo n.º 43
0
 def write(self, string):
     if string.endswith('\n'):
         self.data.append(string[:-1])
         self.flush()
     else:
         self.data.append(string)
Ejemplo n.º 44
0
def python_file_type(string):
    if not string.endswith(".py"):
        msg = "%r is not a Python file" % string
        raise argparse.ArgumentTypeError(msg)
    return string
Ejemplo n.º 45
0
def palindrome(string,maxlen):
	palindromeList = []
	length = len(string)
	suffDict = {}
	lcp = []
	suffArray = []
	suffLexic = []
	rev = string[::-1]
	string = string+"$"+rev
	#print(string)
	suffDict[string] = 1
	suffLexic.append(string) 
	for i in range(1,len(string)):
		suffDict[string[i:]] = i+1 
		suffLexic.append(string[i:])
	#print(suffDict)
	suffLexic = sorted(suffLexic, key=str.lower)
	for i in suffLexic:
		suffArray.append(suffDict[i])
	#print(suffArray)
	#print(suffLexic)
	lcp.append(0)
	i=1
	while i<(len(suffLexic)):
		k = 0
		count = 0
		while (k < len(suffLexic[i]) and k < len(suffLexic[i-1]) and suffLexic[i][k] == suffLexic[i-1][k]) :
			count = count+1
			k = k+1
		#print(count)
		lcp.append(count)
		i = i+1
	#print("LCP",lcp)
			
	i=0
	maxv = 0
	mindex = []
	found = False
	index = 0
	iarray = []
	LCP = lcp
	while(found== False):
		i = 0
		maxv = 0
		index = 0
		while i < len(lcp):
			if(lcp[i]>maxv and (i not in mindex)):
				maxv = lcp[i]
				index = i
			i = i+1
		iarray = [i for i,x in enumerate(lcp) if x==maxv]
		for i in iarray:
			mindex.append(i)
		for index in iarray:
				if((string.endswith(suffLexic[index-1]) and (len(suffLexic[index-1]) > length)  and string.endswith(suffLexic[index],length+1)) or (string.endswith(suffLexic[index]) and (len(suffLexic[index]) > length) and string.endswith(suffLexic[index-1],length+1)) ):
				
					found = True
					if(maxv>=maxlen):
						palindromeList.append(suffLexic[index-1][:maxv])


		palindromeFinal = []
		for i in palindromeList :
			k = 1
			palindromeFinal.append(i)
			while k <= (len(i)//2):
				s = i[k:(len(i)-k)]
				if(len(s)>=maxlen):
					palindromeFinal.append(s)
				k = k+1
			
	return palindromeFinal
Ejemplo n.º 46
0
 def remove_brackets(self, string):
     if string.startswith('(') and string.endswith(')'):
         return string[1:-1]
     else:
         return string
Ejemplo n.º 47
0
def removesuffix(string, suffix):
    """Implementation of str.removesuffix() function available for Python versions lower than 3.9."""
    if suffix and string.endswith(suffix):
        return string[:-len(suffix)]
    else:
        return string
Ejemplo n.º 48
0
def nts(string):
    """Ensures that a string will not end with a trailing slash"""
    if string.endswith('/'):
        return string[:-1]
    return string
Ejemplo n.º 49
0
def ParseValue(string):
    string = string.strip()
    if string.startswith('[') and string.endswith(']'):
        return string.lstrip('[').rstrip(']').split()
    else:
        return string
Ejemplo n.º 50
0
 ...]
reviewWords.index("pickle")
-46 # the word position
review.find("pickle")
-238 #charactersinto review that the word appears
review.count("love")
-2
review.lower().count("love")
-3

string.punctuation
[x for x in review if not x in string.punctuation]
''.join([x for x in review if not x in string.punctuation])

string.startswith()(etc.)
string.endswith()(etc.)
string.isalpha()
string.strip()
string.lstrip()
string.rstrip()

#L3 Processing Times and Dates in Python
# Time.strptime : convert a time string to a structured time object
# Time.strftime : convert a time object to a string
# Time.maketime/calendar.timegem: convert a time object to a number
# Time.gmtime: convert a number to a time object
import time
import calendar
timeString = "2018-07-26 01:36:02"
timeStruct = time.strptime(timeString, "%Y-%m-%d %H:%M:%S")
timeStruct
Ejemplo n.º 51
0
 def write(self, string):
     if string.endswith('\n'):
         self.data.append(string[:-1])
         self.flush()
     else:
         self.data.append(string)
Ejemplo n.º 52
0
def endingThing(string, ending, dictionary) :
	if not dictionary.has_key(ending) : dictionary[ending] = []
	if string.endswith(ending) :
		dictionary[ending].append(string)
	return dictionary
Ejemplo n.º 53
0
def remove_punct(string):
    """Remove common punctuation marks."""
    if string.endswith("?"):
        string = string[:-1]
    return string.replace(",", "").replace(".", "").replace(";", "").replace("!", "")
Ejemplo n.º 54
0
def parse_string(string, code=False, resv=False):
    if string.startswith("ASCII."):
        return hexlify(string[6:].encode()).decode()
    elif string.startswith("TIMES(") and string.endswith(")") and tryconvert(
            string[6:].split(",")[0].strip(), int):
        try:
            times = int(string[6:].split(",")[0].strip())
            value = ",".join(
                value_part
                for value_part in string[6:].split(",")[1:])[:-1].strip()
            value = parse_string(value) * times
        except RecursionError:
            print("To much recursion while handling TIMES macro.")
            exit(1)
        except Exception as e:
            print("Error while handling TIMES macro. Error: %s" % str(e))
            exit(1)
        return value
    elif resv and string.startswith("resv(") and string.endswith(
            ")") and tryconvert(string[5:][:-1].strip(), int):
        if int(string[5:][:-1].strip()) <= 4294967295:
            return int(string[5:][:-1].strip())
        else:
            print("Error while handling resv macro. Number too big. (>2^32)")
            exit(1)
    elif string.startswith("POINTER(") and string.endswith(")") and tryconvert(
            string[8:][:-1].strip(), int):
        if int(string[8:][:-1].strip()) <= unpack("P",
                                                  b'\xff' * scalcsize("P"))[0]:
            try:
                return hexlify(pack("P",
                                    int(string[8:][:-1].strip()))).decode()
            except Exception as e:
                print("Error while handling POINTER macro. Error: %s" % str(e))
                exit(1)
        else:
            print(
                "Error while handling POINTER macro. Number is too big. (>2^%d)"
                % scalcsize("P") * 8)
            exit(1)
    elif string.startswith("LONG(") and string.endswith(")") and tryconvert(
            string[5:][:-1].strip(), int):
        if int(string[5:][:-1].strip()) <= 18446744073709551615:
            try:
                return hexlify(pack("L",
                                    int(string[5:][:-1].strip()))).decode()
            except Exception as e:
                print("Error while handling LONG macro. Error: %s" % str(e))
                exit(1)
        else:
            print(
                "Error while handling LONG macro. Number is too big. (>2^64)")
            exit(1)
    elif string.startswith("INT(") and string.endswith(")") and tryconvert(
            string[4:][:-1].strip(), int):
        if int(string[4:][:-1].strip()) <= 4294967295:
            try:
                return hexlify(pack("I",
                                    int(string[4:][:-1].strip()))).decode()
            except Exception as e:
                print("Error while handling INT macro. Error: %s" % str(e))
                exit(1)
        else:
            print("Error while handling INT macro. Number too big. (>2^32)")
            exit(1)
    elif string.startswith("SHORT(") and string.endswith(")") and tryconvert(
            string[6:][:-1].strip(), int):
        if int(string[6:][:-1].strip()) <= 65535:
            try:
                return hexlify(pack("H",
                                    int(string[6:][:-1].strip()))).decode()
            except Exception as e:
                print("Error while handling SHORT macro. Error: %s" % str(e))
                exit(1)
        else:
            print("Error while handling SHORT macro. Number too big. (>65535)")
            exit(1)
    elif string.startswith("BYTE(") and string.endswith(")") and tryconvert(
            string[5:][:-1].strip(), int):
        if int(string[5:][:-1].strip()) <= 256:
            try:
                return hexlify(pack("B",
                                    int(string[5:][:-1].strip()))).decode()
            except Exception as e:
                print("Error while handling BYTE macro. Error: %s" % str(e))
                exit(1)
        else:
            print("Error while handling BYTE macro. Number too big. (>256)")
            exit(1)
    elif string in list(environment.variables.keys()) and not code:
        return environment.variables[string][2]
    elif tryconvert(string, unhexlify):
        return string
    elif not code:
        print("Unidentified value type: %s" % string)
        exit(1)
    else:
        return string
Ejemplo n.º 55
0
def nts(string):
    """Ensures that a string will not end with a trailing slash"""
    if string.endswith('/'):
        return string[:-1]
    return string
Ejemplo n.º 56
0
def ParseValue(string):
    string = string.strip()
    if string.startswith("[") and string.endswith("]"):
        return string.lstrip("[").rstrip("]").split()
    else:
        return string
Ejemplo n.º 57
0
def ParseValue(string):
  string = string.strip()
  if string.startswith('[') and string.endswith(']'):
    return string.lstrip('[').rstrip(']').split()
  else:
    return string
Ejemplo n.º 58
0
 def endat(self, string, ending):
     if string.endswith(ending):
         return len(string) - len(ending)
     return 0