Check a file if the same thing is written 3 times

Question:

I’m very new to accessing files. I want to see if the same thing is written 3 times in a text file and if it is replace it with something that is written only one time so it is balanced.

Any idea how I can do that?
Edit: if it is possible only if they are in 2 separate lines in the file
Edit 2 : file example:

John-Alex
John-Kyle
John-Ben
Ben-Gary

So John in the 3rd line should be replaced by Kyle or Alex or Gary.

Maybe separate everything and if let’s say John is found 3 times, then only one of the John found in the file be replaced by Gary, Kyle or Alex as they are in a different line and there is only one of them. So let’s say one of the John is replaced by Alex like this:

John-Alex
Alex-Kyle
John-Ben
Ben-Gary

As you can see, John is replaced by Alex and it isn’t in the same line as Alex as that would be Alex-Alex and that is not okay.

Asked By: Koneko Sama

||

Answers:

Here is the code that will check if a line in a file is repeated 3 or more times:

names = {}
with open("your_file.txt", "r") as file:
    text = file.read()
    lines = file.readlines()

for line in lines:
    for name in line.split("-"):
        if name in names.keys():
            names[name] += 1
        else:
            names[name] = 1

names_with_count_1 = []
for name, count in names.items():
    if count == 1:
        names_with_count_1.append(name)

for name, count in names.items():
    if count >= 3:
        text.replace(text.find(name, 3), names[names_with_count_1[0]])
        names_with_count_1.remove(names_with_count_1[0])

with open("your_file.txt", "w") as file:
    file.write(text)
Answered By: BokiX
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.