Python Forum
Replace String with increasing numer [SOLVED]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace String with increasing numer [SOLVED]
#1
Hello everybody,

I have a text-file with multiple strings which I want to be replaced by an increasing number.
For example there is there the string "example" 7 times in it and I want to replace "example" with a number:

Before:
This example is an example on how to make an example with the word example. the example ends here with an example. for example.

After
This 1 is an 2 on how to make an 3 with the word 4. the 5 ends here with an 6. for 7.

How do you do that?
Also, while developing the script, I want it to look for every text-file inside my folder not just a specified file (see code below).

This is what I have now but it doens't work:

#!/usr/bin/env python3

fileCounter = 1

with open('*.txt', 'r') as file :
  filedata = file.read()

filedata = filedata.replace('example', ''+fileCounter)

with open('*.txt', 'w') as file:
  file.write(filedata)
Reply
#2
If it's not too huge, I'd just loop over it. But for very large files, that's inefficient.

paragraph = """This example is an example on how to make an
example with the word example. the example ends here with an example. for example"""

target = "example"
counter = 0
while target in paragraph:
    counter += 1
    paragraph = paragraph.replace(target, str(counter), 1)

print(paragraph)
If it is huge, time to break out regex parser. I think there should be a simpler way to write a callable incrementor, but this will do for now.

import re

target = "example"

def str_counter(match_object):
    str_counter.count += 1
    return str(str_counter.count)
str_counter.count = 0

paragraph = """This example is an example on how to make an
example with the word example. the example ends here with an example. for example"""

paragraph = re.sub(re.escape(target), str_counter, paragraph)

print(paragraph)
Reply
#3
(Aug-06-2021, 09:05 PM)bowlofred Wrote: If it's not too huge, I'd just loop over it. But for very large files, that's inefficient.

paragraph = """This example is an example on how to make an
example with the word example. the example ends here with an example. for example"""

target = "example"
counter = 0
while target in paragraph:
    counter += 1
    paragraph = paragraph.replace(target, str(counter), 1)

print(paragraph)
If it is huge, time to break out regex parser. I think there should be a simpler way to write a callable incrementor, but this will do for now.

import re

target = "example"

def str_counter(match_object):
    str_counter.count += 1
    return str(str_counter.count)
str_counter.count = 0

paragraph = """This example is an example on how to make an
example with the word example. the example ends here with an example. for example"""

paragraph = re.sub(re.escape(target), str_counter, paragraph)

print(paragraph)

Hey, thanks for replying.
Where do I have to define that my script should check in text-files? And what's the difference between target and paragraph?
Reply
#4
maybe like this?

mytext = """hello example
example test
world example
example to learn
best example
example new
better example"""

result = ""

filedata = mytext.splitlines()

i = 1
for line in filedata: 
    if 'example' in line:
        line = line.replace("example", f"example_{str(i)}")
        i += 1
    result += f"{line}\n"

print(result)
Output:
hello example_1 example_2 test world example_3 example_4 to learn best example_5 example_6 new better example_7
Reply
#5
(Aug-06-2021, 09:13 PM)AlphaInc Wrote: Where do I have to define that my script should check in text-files?

In my example, the text is already in a string called paragraph. In your example, you read in the text file to a variable called filedata. They're both just strings. Rename them how you want.

Quote:And what's the difference between target and paragraph?

One is what you're looking to replace, one is where you're looking and replacing it. Did you try running the code?
Reply
#6
(Aug-06-2021, 09:36 PM)bowlofred Wrote:
(Aug-06-2021, 09:13 PM)AlphaInc Wrote: Where do I have to define that my script should check in text-files?

In my example, the text is already in a string called paragraph. In your example, you read in the text file to a variable called filedata. They're both just strings. Rename them how you want.

Quote:And what's the difference between target and paragraph?

One is what you're looking to replace, one is where you're looking and replacing it. Did you try running the code?

Yeah I did but it did not change my text-file. I changed it a little bit to this.

import re

target = "example"

def str_counter(match_object):
    str_counter.count += 1
    return str(str_counter.count)
str_counter.count = 0

with open('text.txt', 'r') as file :
  filedata = file.read()

filedata = re.sub(re.escape(target), str_counter, filedata)

print(filedata)
This works fine except for one last thing - how can I save the printed output to the same file and overwrite it?
Reply
#7
paragraph = (
    "This example is an example on how to make an example with the"
    " word example. the example ends here with an example. for example"
)

target = "example"


def replace_occurence_count(paragraph: str, target: str) -> str:
    occurances = paragraph.count(target)
    for number in range(1, occurances + 1):
        paragraph = paragraph.replace(target, f"{number}", 1)
    return paragraph


print(replace_occurence_count(paragraph, target))
Output:
This 1 is an 2 on how to make an 3 with the word 4. the 5 ends here with an 6. for 7

@bowlofred
For a simple counter, you can use itertools count
from itertools import count

counter = count(1)
print(next(counter))
print(next(counter))
Output:
1 2
Reply
#8
(Aug-06-2021, 10:11 PM)Yoriz Wrote: @bowlofred
For a simple counter, you can use itertools count

Yes. But for re.sub(), I needed a callable that returns the answer, not an iterator. I imagine there is something in functools that will create such a function for me, but I hadn't yet found such a solution.
Reply
#9
(Aug-06-2021, 10:00 PM)AlphaInc Wrote: This works fine except for one last thing - how can I save the printed output to the same file and overwrite it?

In your code you read the data from the file into a variable with <file>.read(). You can do the opposite (on a file that has been opened for writing) with <file>.write().


# read in filedata
with open('text.txt', 'r') as file :
    filedata = file.read()

# do stuff with filedata here

# write filedata out here (overwriting the file)
with open('text.txt', 'w') as file:
    file.write(filedata)
This is a bit dangerous because for a period of time, there is no data on disk. For a production script, I'd change this to write the file to another name, then after the write has succeeded, rename the file.
Reply
#10
(Aug-06-2021, 10:55 PM)bowlofred Wrote: Yes. But for re.sub(), I needed a callable that returns the answer, not an iterator. I imagine there is something in functools that will create such a function for me, but I hadn't yet found such a solution.
Call it with next as I did in the example above.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 774 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,217 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,589 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into &lt;/&gt;? Winfried 0 1,530 Sep-03-2022, 11:21 PM
Last Post: Winfried
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,124 Aug-19-2022, 08:07 PM
Last Post: Winfried
  Find and Replace numbers in String giddyhead 2 1,244 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Adding string after every 3rd charater [SOLVED] AlphaInc 2 1,260 Jul-11-2022, 09:22 AM
Last Post: ibreeden
Question [SOLVED] Delete specific characters from string lines EnfantNicolas 4 2,228 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,161 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
Thumbs Up Parsing a YAML file without changing the string content..?, Flask - solved. SpongeB0B 2 2,280 Aug-05-2021, 08:02 AM
Last Post: SpongeB0B

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020