python managing redundant data by incrementing no. in a text file
Question: I am new to python.I have a text file, i need to avoid the redundancy not by
deleting ,but by incrementing the number in a text file if the lines are found
to be same.

Please help!Answers will be appreciated! eg of a random text file:

    
    
    hello ram1
    hello ram1
    hello gate1
    hello gate1
    

Expected output:

    
    
    hello ram1
    hello ram2
    hello gate1
    hello gate2
    


Answer: Using regular expression and
[`collections.defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict):

    
    
    from collections import defaultdict
    import re
    
    numbers = defaultdict(int)
    with open('/path/to/textfile.txt') as f:
        for line in f:
            line = re.sub(r'\d+', '', line.rstrip())  # Remove numbers.
            numbers[line] += 1  # Increment number for the same line
            print('{}{}'.format(line, numbers[line]))
    

* * *

**UPDATE** using slice notation, dictionary.

    
    
    import re
    
    numbers = {}
    with open('1.txt') as f:
        for line in f:
            row = re.split(r'(\d+)', line.strip())
            words = tuple(row[::2])  # Extract non-number parts to use it as key
            if words not in numbers:
                numbers[words] = [int(n) for n in row[1::2]]  # extract number parts.
            numbers[words] = [n+1 for n in numbers[words]]  # Increase numbers.
            row[1::2] = map(str, numbers[words])  # Assign back numbers
            print(''.join(row))
    

