Python string.find() Examples

The following are 30 code examples for showing how to use string.find(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: razzy-spinner   Author: rafasashi   File: wntools.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getIndex(form, pos='noun'):
    """Search for _form_ in the index file corresponding to
    _pos_. getIndex applies to _form_ an algorithm that replaces
    underscores with hyphens, hyphens with underscores, removes
    hyphens and underscores, and removes periods in an attempt to find
    a form of the string that is an exact match for an entry in the
    index file corresponding to _pos_.  getWord() is called on each
    transformed string until a match is found or all the different
    strings have been tried. It returns a Word or None."""
    def trySubstitutions(trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor(pos)):
        if lookup and dictionary.has_key(form):
            return dictionary[form]
        elif substitutions:
            (old, new) = substitutions[0]
            substitute = string.replace(form, old, new) and substitute != form
            if substitute and dictionary.has_key(substitute):
                return dictionary[substitute]
            return              trySubstitutions(trySubstitutions, form, substitutions[1:], lookup=0) or \
                (substitute and trySubstitutions(trySubstitutions, substitute, substitutions[1:]))
    return trySubstitutions(returnMatch, form, GET_INDEX_SUBSTITUTIONS) 
Example 2
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 3
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _testKeys(self):
	"""Verify that index lookup can find each word in the index file."""
	print "Testing: ", self
	file = open(self.indexFile.file.name, _FILE_OPEN_MODE)
	counter = 0
	while 1:
	    line = file.readline()
	    if line == '': break
	    if line[0] != ' ':
		key = string.replace(line[:string.find(line, ' ')], '_', ' ')
		if (counter % 1000) == 0:
		    print "%s..." % (key,),
		    import sys
		    sys.stdout.flush()
		counter = counter + 1
		self[key]
	file.close()
	print "done." 
Example 4
Project: razzy-spinner   Author: rafasashi   File: wntools.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getIndex(form, pos='noun'):
    """Search for _form_ in the index file corresponding to
    _pos_. getIndex applies to _form_ an algorithm that replaces
    underscores with hyphens, hyphens with underscores, removes
    hyphens and underscores, and removes periods in an attempt to find
    a form of the string that is an exact match for an entry in the
    index file corresponding to _pos_.  getWord() is called on each
    transformed string until a match is found or all the different
    strings have been tried. It returns a Word or None."""
    def trySubstitutions(trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor(pos)):
        if lookup and dictionary.has_key(form):
            return dictionary[form]
        elif substitutions:
            (old, new) = substitutions[0]
            substitute = string.replace(form, old, new) and substitute != form
            if substitute and dictionary.has_key(substitute):
                return dictionary[substitute]
            return              trySubstitutions(trySubstitutions, form, substitutions[1:], lookup=0) or \
                (substitute and trySubstitutions(trySubstitutions, substitute, substitutions[1:]))
    return trySubstitutions(returnMatch, form, GET_INDEX_SUBSTITUTIONS) 
Example 5
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 6
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _testKeys(self):
	"""Verify that index lookup can find each word in the index file."""
	print "Testing: ", self
	file = open(self.indexFile.file.name, _FILE_OPEN_MODE)
	counter = 0
	while 1:
	    line = file.readline()
	    if line == '': break
	    if line[0] != ' ':
		key = string.replace(line[:string.find(line, ' ')], '_', ' ')
		if (counter % 1000) == 0:
		    print "%s..." % (key,),
		    import sys
		    sys.stdout.flush()
		counter = counter + 1
		self[key]
	file.close()
	print "done." 
Example 7
Project: meddle   Author: glmcdona   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def get_build_version():
    """Return the version of MSVC that was used to build Python.

    For Python 2.3 and up, the version number is included in
    sys.version.  For earlier versions, assume the compiler is MSVC 6.
    """

    prefix = "MSC v."
    i = string.find(sys.version, prefix)
    if i == -1:
        return 6
    i = i + len(prefix)
    s, rest = sys.version[i:].split(" ", 1)
    majorVersion = int(s[:-2]) - 6
    minorVersion = int(s[2:3]) / 10.0
    # I don't think paths are affected by minor version in version 6
    if majorVersion == 6:
        minorVersion = 0
    if majorVersion >= 6:
        return majorVersion + minorVersion
    # else we don't know what version of the compiler this is
    return None 
Example 8
Project: meddle   Author: glmcdona   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def find_library_file (self, dirs, lib, debug=0):
        # Prefer a debugging library if found (and requested), but deal
        # with it if we don't have one.
        if debug:
            try_names = [lib + "_d", lib]
        else:
            try_names = [lib]
        for dir in dirs:
            for name in try_names:
                libfile = os.path.join(dir, self.library_filename (name))
                if os.path.exists(libfile):
                    return libfile
        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

    # Helper methods for using the MSVC registry settings 
Example 9
Project: meddle   Author: glmcdona   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """

        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in string.split(os.environ['Path'],';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example 10
Project: meddle   Author: glmcdona   File: cygwinccompiler.py    License: MIT License 6 votes vote down vote up
def get_msvcr():
    """Include the appropriate MSVC runtime library if Python was built
    with MSVC 7.0 or later.
    """
    msc_pos = sys.version.find('MSC v.')
    if msc_pos != -1:
        msc_ver = sys.version[msc_pos+6:msc_pos+10]
        if msc_ver == '1300':
            # MSVC 7.0
            return ['msvcr70']
        elif msc_ver == '1310':
            # MSVC 7.1
            return ['msvcr71']
        elif msc_ver == '1400':
            # VS2005 / MSVC 8.0
            return ['msvcr80']
        elif msc_ver == '1500':
            # VS2008 / MSVC 9.0
            return ['msvcr90']
        else:
            raise ValueError("Unknown MS Compiler version %s " % msc_ver) 
Example 11
Project: ironpython2   Author: IronLanguages   File: msvccompiler.py    License: Apache License 2.0 6 votes vote down vote up
def get_build_version():
    """Return the version of MSVC that was used to build Python.

    For Python 2.3 and up, the version number is included in
    sys.version.  For earlier versions, assume the compiler is MSVC 6.
    """

    prefix = "MSC v."
    i = string.find(sys.version, prefix)
    if i == -1:
        return 6
    i = i + len(prefix)
    s, rest = sys.version[i:].split(" ", 1)
    majorVersion = int(s[:-2]) - 6
    minorVersion = int(s[2:3]) / 10.0
    # I don't think paths are affected by minor version in version 6
    if majorVersion == 6:
        minorVersion = 0
    if majorVersion >= 6:
        return majorVersion + minorVersion
    # else we don't know what version of the compiler this is
    return None 
Example 12
Project: ironpython2   Author: IronLanguages   File: msvccompiler.py    License: Apache License 2.0 6 votes vote down vote up
def find_library_file (self, dirs, lib, debug=0):
        # Prefer a debugging library if found (and requested), but deal
        # with it if we don't have one.
        if debug:
            try_names = [lib + "_d", lib]
        else:
            try_names = [lib]
        for dir in dirs:
            for name in try_names:
                libfile = os.path.join(dir, self.library_filename (name))
                if os.path.exists(libfile):
                    return libfile
        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

    # Helper methods for using the MSVC registry settings 
Example 13
Project: ironpython2   Author: IronLanguages   File: msvccompiler.py    License: Apache License 2.0 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """

        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in string.split(os.environ['Path'],';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example 14
Project: ironpython2   Author: IronLanguages   File: cygwinccompiler.py    License: Apache License 2.0 6 votes vote down vote up
def get_msvcr():
    """Include the appropriate MSVC runtime library if Python was built
    with MSVC 7.0 or later.
    """
    msc_pos = sys.version.find('MSC v.')
    if msc_pos != -1:
        msc_ver = sys.version[msc_pos+6:msc_pos+10]
        if msc_ver == '1300':
            # MSVC 7.0
            return ['msvcr70']
        elif msc_ver == '1310':
            # MSVC 7.1
            return ['msvcr71']
        elif msc_ver == '1400':
            # VS2005 / MSVC 8.0
            return ['msvcr80']
        elif msc_ver == '1500':
            # VS2008 / MSVC 9.0
            return ['msvcr90']
        else:
            raise ValueError("Unknown MS Compiler version %s " % msc_ver) 
Example 15
Project: BinderFilter   Author: dxwu   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def get_build_version():
    """Return the version of MSVC that was used to build Python.

    For Python 2.3 and up, the version number is included in
    sys.version.  For earlier versions, assume the compiler is MSVC 6.
    """

    prefix = "MSC v."
    i = string.find(sys.version, prefix)
    if i == -1:
        return 6
    i = i + len(prefix)
    s, rest = sys.version[i:].split(" ", 1)
    majorVersion = int(s[:-2]) - 6
    minorVersion = int(s[2:3]) / 10.0
    # I don't think paths are affected by minor version in version 6
    if majorVersion == 6:
        minorVersion = 0
    if majorVersion >= 6:
        return majorVersion + minorVersion
    # else we don't know what version of the compiler this is
    return None 
Example 16
Project: BinderFilter   Author: dxwu   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def find_library_file (self, dirs, lib, debug=0):
        # Prefer a debugging library if found (and requested), but deal
        # with it if we don't have one.
        if debug:
            try_names = [lib + "_d", lib]
        else:
            try_names = [lib]
        for dir in dirs:
            for name in try_names:
                libfile = os.path.join(dir, self.library_filename (name))
                if os.path.exists(libfile):
                    return libfile
        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

    # Helper methods for using the MSVC registry settings 
Example 17
Project: BinderFilter   Author: dxwu   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """

        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in string.split(os.environ['Path'],';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example 18
Project: Computable   Author: ktraunmueller   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def get_build_version():
    """Return the version of MSVC that was used to build Python.

    For Python 2.3 and up, the version number is included in
    sys.version.  For earlier versions, assume the compiler is MSVC 6.
    """

    prefix = "MSC v."
    i = string.find(sys.version, prefix)
    if i == -1:
        return 6
    i = i + len(prefix)
    s, rest = sys.version[i:].split(" ", 1)
    majorVersion = int(s[:-2]) - 6
    minorVersion = int(s[2:3]) / 10.0
    # I don't think paths are affected by minor version in version 6
    if majorVersion == 6:
        minorVersion = 0
    if majorVersion >= 6:
        return majorVersion + minorVersion
    # else we don't know what version of the compiler this is
    return None 
Example 19
Project: Computable   Author: ktraunmueller   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def find_library_file (self, dirs, lib, debug=0):
        # Prefer a debugging library if found (and requested), but deal
        # with it if we don't have one.
        if debug:
            try_names = [lib + "_d", lib]
        else:
            try_names = [lib]
        for dir in dirs:
            for name in try_names:
                libfile = os.path.join(dir, self.library_filename (name))
                if os.path.exists(libfile):
                    return libfile
        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

    # Helper methods for using the MSVC registry settings 
Example 20
Project: Computable   Author: ktraunmueller   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """

        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in string.split(os.environ['Path'],';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example 21
Project: Computable   Author: ktraunmueller   File: cygwinccompiler.py    License: MIT License 6 votes vote down vote up
def get_msvcr():
    """Include the appropriate MSVC runtime library if Python was built
    with MSVC 7.0 or later.
    """
    msc_pos = sys.version.find('MSC v.')
    if msc_pos != -1:
        msc_ver = sys.version[msc_pos+6:msc_pos+10]
        if msc_ver == '1300':
            # MSVC 7.0
            return ['msvcr70']
        elif msc_ver == '1310':
            # MSVC 7.1
            return ['msvcr71']
        elif msc_ver == '1400':
            # VS2005 / MSVC 8.0
            return ['msvcr80']
        elif msc_ver == '1500':
            # VS2008 / MSVC 9.0
            return ['msvcr90']
        else:
            raise ValueError("Unknown MS Compiler version %s " % msc_ver) 
Example 22
Project: oss-ftp   Author: aliyun   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def get_build_version():
    """Return the version of MSVC that was used to build Python.

    For Python 2.3 and up, the version number is included in
    sys.version.  For earlier versions, assume the compiler is MSVC 6.
    """

    prefix = "MSC v."
    i = string.find(sys.version, prefix)
    if i == -1:
        return 6
    i = i + len(prefix)
    s, rest = sys.version[i:].split(" ", 1)
    majorVersion = int(s[:-2]) - 6
    minorVersion = int(s[2:3]) / 10.0
    # I don't think paths are affected by minor version in version 6
    if majorVersion == 6:
        minorVersion = 0
    if majorVersion >= 6:
        return majorVersion + minorVersion
    # else we don't know what version of the compiler this is
    return None 
Example 23
Project: oss-ftp   Author: aliyun   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def find_library_file (self, dirs, lib, debug=0):
        # Prefer a debugging library if found (and requested), but deal
        # with it if we don't have one.
        if debug:
            try_names = [lib + "_d", lib]
        else:
            try_names = [lib]
        for dir in dirs:
            for name in try_names:
                libfile = os.path.join(dir, self.library_filename (name))
                if os.path.exists(libfile):
                    return libfile
        else:
            # Oops, didn't find it in *any* of 'dirs'
            return None

    # find_library_file ()

    # Helper methods for using the MSVC registry settings 
Example 24
Project: oss-ftp   Author: aliyun   File: msvccompiler.py    License: MIT License 6 votes vote down vote up
def find_exe(self, exe):
        """Return path to an MSVC executable program.

        Tries to find the program in several places: first, one of the
        MSVC program search paths from the registry; next, the directories
        in the PATH environment variable.  If any of those work, return an
        absolute path that is known to exist.  If none of them work, just
        return the original program name, 'exe'.
        """

        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        # didn't find it; try existing path
        for p in string.split(os.environ['Path'],';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe 
Example 25
Project: oss-ftp   Author: aliyun   File: cygwinccompiler.py    License: MIT License 6 votes vote down vote up
def get_msvcr():
    """Include the appropriate MSVC runtime library if Python was built
    with MSVC 7.0 or later.
    """
    msc_pos = sys.version.find('MSC v.')
    if msc_pos != -1:
        msc_ver = sys.version[msc_pos+6:msc_pos+10]
        if msc_ver == '1300':
            # MSVC 7.0
            return ['msvcr70']
        elif msc_ver == '1310':
            # MSVC 7.1
            return ['msvcr71']
        elif msc_ver == '1400':
            # VS2005 / MSVC 8.0
            return ['msvcr80']
        elif msc_ver == '1500':
            # VS2008 / MSVC 9.0
            return ['msvcr90']
        else:
            raise ValueError("Unknown MS Compiler version %s " % msc_ver) 
Example 26
Project: pivy   Author: coin3d   File: Main.py    License: ISC License 6 votes vote down vote up
def __init__(self, obj, interval=1, file=None, overwrite=False):
        if file is None:
            file = sys.stdout

        self.obj = obj
        self.file = file
        self.interval = interval
        self.overwrite = overwrite

        if callable(obj):
            self.func = obj
        elif SCons.Util.is_List(obj):
            self.func = self.spinner
        elif string.find(obj, self.target_string) != -1:
            self.func = self.replace_string
        else:
            self.func = self.string 
Example 27
Project: pivy   Author: coin3d   File: Main.py    License: ISC License 6 votes vote down vote up
def find_deepest_user_frame(tb):
    """
    Find the deepest stack frame that is not part of SCons.

    Input is a "pre-processed" stack trace in the form
    returned by traceback.extract_tb() or traceback.extract_stack()
    """
    
    tb.reverse()

    # find the deepest traceback frame that is not part
    # of SCons:
    for frame in tb:
        filename = frame[0]
        if string.find(filename, os.sep+'SCons'+os.sep) == -1:
            return frame
    return tb[0] 
Example 28
Project: pivy   Author: coin3d   File: msvs.py    License: ISC License 6 votes vote down vote up
def msvs_parse_version(s):
    """
    Split a Visual Studio version, which may in fact be something like
    '7.0Exp', into is version number (returned as a float) and trailing
    "suite" portion.
    """
    num, suite = version_re.match(s).groups()
    return float(num), suite

# This is how we re-invoke SCons from inside MSVS Project files.
# The problem is that we might have been invoked as either scons.bat
# or scons.py.  If we were invoked directly as scons.py, then we could
# use sys.argv[0] to find the SCons "executable," but that doesn't work
# if we were invoked as scons.bat, which uses "python -c" to execute
# things and ends up with "-c" as sys.argv[0].  Consequently, we have
# the MSVS Project file invoke SCons the same way that scons.bat does,
# which works regardless of how we were invoked. 
Example 29
Project: pivy   Author: coin3d   File: hpc++.py    License: ISC License 6 votes vote down vote up
def generate(env):
    """Add Builders and construction variables for g++ to an Environment."""
    cplusplus.generate(env)

    if acc:
        env['CXX']        = acc or 'aCC'
        env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS +Z')
        # determine version of aCC
        line = os.popen(acc + ' -V 2>&1').readline().rstrip()
        if string.find(line, 'aCC: HP ANSI C++') == 0:
            env['CXXVERSION'] = string.split(line)[-1]

        if env['PLATFORM'] == 'cygwin':
            env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
        else:
            env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS +Z') 
Example 30
Project: pivy   Author: coin3d   File: midl.py    License: ISC License 6 votes vote down vote up
def midl_emitter(target, source, env):
    """Produces a list of outputs from the MIDL compiler"""
    base, ext = SCons.Util.splitext(str(target[0]))
    tlb = target[0]
    incl = base + '.h'
    interface = base + '_i.c'
    t = [tlb, incl, interface]

    midlcom = env['MIDLCOM']

    if string.find(midlcom, '/proxy') != -1:
        proxy = base + '_p.c'
        t.append(proxy)
    if string.find(midlcom, '/dlldata') != -1:
        dlldata = base + '_data.c'
        t.append(dlldata)
    
    return (t,source)