Python word in file change
Question: I am trying to change the words that are nouns in a text to "noun". I am
having trouble. Here is what I have so far.

    
    
    def noun(file):
        for word in file:
            for ch in word:
                if ch[-1:-3] == "ion" or ch[-1:-3] == "ism" or ch[-1:-3] == "ity":
                    word = "noun"
            if file(word-1) == "the" and (file(word+1)=="of" or file(word+1) == "on" 
                word = "noun"
              #  words that appear after the 
            return outfile 
    

Any ideas?


Answer: Your slices are empty:

    
    
    >>> 'somethingion'[-1:-3]
    ''
    

because the endpoint lies before the start. You could just use `[-3:]` here:

    
    
    >>> 'somethingion'[-3:]
    'ion'
    

But you'd be better of using
[`str.endswith()`](https://docs.python.org/2/library/stdtypes.html#str.endswith)
instead:

    
    
    ch.endswith(("ion", "ism", "ity"))
    

The function will return `True` if the string ends with any of the 3 given
strings.

Not that `ch` is actually a word; if `word` is a string, then `for ch in word`
iterates over _individual characters_ , and those are never going to end in
3-character strings, being only one character long themselves.

Your attempts to look at the next and previous words are also going to fail;
you cannot use a list or file object as a callable, let alone use `file(word -
1)` as a meaningful expression (a string `- 1` fails, as well as `file(...)`).

Instead of looping over the 'word', you could use a regular expression here:

    
    
    import re
    
    nouns = re.compile(r'(?<=\bthe\b)(\s*\w+(?:ion|ism|ity)\s*)(?=\b(?:of|on)\b)')
    
    some_text = nouns.sub(' noun ', some_text)
    

This looks for words ending in your three substrings, but only if preceded by
`the` and followed by `of` or `on` and replaces those with `noun`.

Demo:

    
    
    >>> import re
    >>> nouns = re.compile(r'(?<=\bthe\b)(\s*\w+(?:ion|ism|ity)\s*)(?=\b(?:of|on)\b)')
    >>> nouns.sub(' noun ', 'the scion on the prism of doom')
    'the noun on the noun of doom'
    

