0

I'm newer to Python and need help with my program. I need the number between the quotes following "apple." to be replaced with new randomly generated numbers. I've been stuck on this for a while and would appreciate any help!

Example Below

demo_input.txt = #demo_input is a txt file
{
9apple."234"
orangetaco""
testrocket""
3apple."923"
mangofruit""
1apple."148"
}

demo_output.txt = #demo_output is a txt file
#each of the new random numbers need to be different
{
9apple."657"
orangetaco""
testrocket""
3apple."883"
mangofruit""
1apple."102"
}
CypherB1t
  • 1
  • 1
  • i think you can use regular expression to find and replace it by reading line by line – kei nagae May 16 '22 at 06:11
  • 1
    Your input file format is quite ad hoc. Write a parser for it, or (much better) change whatever produces these files so it uses a standard machine-readable format like CSV, JSON, YAML, XML, or etc. – tripleee May 16 '22 at 06:12

3 Answers3

0

Assuming the text file will always take the form described above, you can use the following approach. Loop through each line, checking if it contains the key word. Generate a new random number and add the updated line to the output string. Print the output string to the file.

import random

file = open("input.txt", "r")
output = ""
for line in file:
    if line.__contains__("apple"):
        for i in range(len(line)):
            if line[i] == "\"":
                output += line[:line.find("\"")+1] + str(random.randint(100, 999)) + "\"\n"
                break
    else:
        output += line

file.close()

out = open("input.txt", "w")
out.write(output)
0

Here is an approach you can use to achieve this. Explanations as part of code itself.

import re


def replace(content, replace_with, prefix="apple"):
    """
    with re, find the pattern (?<=apple\.)("\d+"), and find the numerical to replace
    replace it with the random value you want.
    Do this for every line in your text.
    :param content: The text content, read from file or whatever pass it as a string
    :param replace_with: the value you want to replace the value with.
    :param prefix: the text before the number, default is apple.
    :return: the content with the replaced value
    """

    # The regex used was (?<=apple\.)("\d+"), which is a lookbehind assertion
    # that matches the text "apple." and then a group of digits.
    return "\n".join([re.sub(rf'(?<={prefix}\.)("\d+")', f'"{replace_with}"', line) for line in content.split("\n")])


text = '''
{
9apple."234"
orangetaco""
testrocket""
3apple."923"
mangofruit""
1apple."148"
}
'''

print(replace(text, 345, "apple"))

This will give you a transformed text like

{
9apple."345"
orangetaco""
testrocket""
3apple."345"
mangofruit""
1apple."345"
}

You can also refer this answer, to learn more about the regex that was used.

Kris
  • 8,680
  • 4
  • 39
  • 67
0

you could use python re module like this here I am not sure how your random number are generated but something like this can be used to achieve this

import re
import random

def random_number_generator():
    return f'apple."{random.randint(100, 9999)}"'

pattern = re.compile(r'apple."[0-9]*"')
with open("input.txt") as file,open("out.txt",mode="w") as outfile:
    for line in file.readlines():
        line=re.sub(pattern,random_number_generator(),line)
        outfile.write(line)

or if you need to replace based on the number found you can use following snippet

import re
pattern = re.compile(r'apple."[0-9]*"')
def random_number_generator(matched_string):
    #here you can use match matched_string to generate random numbers
    return 'apple."some random number"'
with open("input.txt") as file,open("out.txt",mode="w") as outfile:
    for line in file.readlines():
        search=pattern.search(line)
        if search:
            line=re.sub(pattern,random_number_generator(search.string),line)
            outfile.write(line)
        else:
            outfile.write(line)
kei nagae
  • 200
  • 1
  • 15