0

What I wanted to do was load in text from a file (1.), and then replace each text piece between two quotes with an Output, which depends on the Input.

Examle of what the whole program would do: Input file:

pet_1 = "Dog"
pet_2 = "Cat"
pet_3 = "Dog"

And Output file would be:

pet_1 = "First Dog"
pet_2 = "First Cat"
pet_3 = "Second Dog"

Here´s how I wanted to do it, but I had no idea how to code:

1.): Load in text from a text file: (this was the only part I could do):

file = open('file.txt', 'r')
string = file.read()
file.close()

2.): Extract text between quotes and put the pieces in a list:

Input:

pet_1 = "Dog"
pet_2 = "Cat"

Output would be: ["Dog", "Cat"]

3.): Modify the items of this list:

For example: ["First Dog", "First Cat"]

4.): Put the text pieces in the correct spot again:

Example:

pet_1 = "Dog"
pet_2 = "Cat"

The reason why I want to do this, is because I have a giant text file with about 4750 lines, and I don´t want to modify it by hand. I hope you understand.

  • 1
    Help you with what? Can you please be more specific about your question? If you tried things that didn't work for you, please share them with us. – Maroun Oct 26 '20 at 14:02
  • Also, how do you get from ```string = file.read()``` to ```pet_1 = "Dog" pet_2 = "Cat"``` I assume you want to split string into a list, then perform an operation on every element in there, e.g. prepend some string and go from there. Maybe create a copy of that list, so you can use it again later, but that's all just guessing. – n00by0815 Oct 26 '20 at 14:14
  • Does this answer your question? [Python replace string pattern with output of function](https://stackoverflow.com/questions/12597370/python-replace-string-pattern-with-output-of-function) – Arman Oct 26 '20 at 16:22
  • Which of the 4 tasks the question sketches are you actually asking about? – MisterMiyagi Oct 27 '20 at 09:26

2 Answers2

0

Not exactly sure what you're trying to do and if it would be affected by case (capital letters) but you could try:

with open('file.txt', 'r') as f:
    string = f.read()

pet_1 = 'Dog'
pet_2 = 'Cat'

something = input("Input: ") + ' '

string = string.replace(pet_1, (something + pet_1))
string = string.replace(pet_2, (something + pet_2))

pet_1 and pet_2 won't be affected and the variables don't need to be 'put back in the correct spot again' if I understand you correctly.

nihilok
  • 1,325
  • 8
  • 12
0

You can use re.sub with a callback function to get a "dynamic" replacement, where you can e.g. call a function based on the string to be replaced. With that, you can use a dictionary, or collections.defaultdict and get the next prefix based on the animal to be replaced.

text = """
pet_1 = "Dog"
pet_2 = "Cat"
pet_3 = "Dog"
"""

import re, collections
count = collections.defaultdict(lambda: iter(["First", "Second", "Third", "Fourth"]))
res = re.sub(r'"([^"]+)"', lambda m: f'"{next(count[m.group(1)])} {m.group(1)}"', text)

Afterwards, res is

pet_1 = "First Dog"
pet_2 = "First Cat"
pet_3 = "Second Dog"

Some more explanation:

  • count is a defaultdict, mapping each word/animal to an iterator of words like "first", "second", etc.
  • re.sub will use a regular expression to find the part within "..." and then use a callback-function to derive the actual replacement
  • the regular expression r'"([^"]+)"' means "a quote, then some characters that are not quotes, then another quote"
  • the lambda is the callback function, creating a format-string that is composed of the next prefix from the iterator associated with (or newly created for) that word, and the word itself, where m.group(1) refers to the part within (...) that was matched in the regular expression

(Obviously, the iter(["First", ...]) might need to be extended with more elements for longer lists, or just use itertools.count(1) to get numbers instead of words.)

tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • Dear tobias_k, thank you for your answer, and please apologise my bad question writing. But for now, the "real" reason is to translate the text pieces. I have no problem with translating in python, but sadly no experience with re or lambda, so it would be really nice if you could write an answer that fits into the context. – Christian Patzl Oct 27 '20 at 09:33
  • @ChristianPatzl I don't understand. Doesn't the answer derive the result you want? Or do you want an answer without `re` and `lambda`? In the latter case: Those are the best tools for that; learn to use them, don't try to work around them. – tobias_k Oct 27 '20 at 09:56
  • the answer is very good but it isn´t exactly what I want. I tried to read the re documentation, but I just don´t understand it – Christian Patzl Oct 27 '20 at 10:00
  • @ChristianPatzl Then what do you want? What do you mean with "translate the text pieces" other than adding the "first", "second" part? – tobias_k Oct 27 '20 at 10:03