简体   繁体   中英

Locating a character in one text file, and replacing it with a character from another

My code so far...

    f = open("words.txt","r")
    words = f.read()
    f = open("solved.txt","r")
    solved = f.read()
    f = open("clues.txt","r")
    clues = f.read()

    def importclues():
        global clues
        global words
        z=0
        for z in clues:
            words.replace(clues[z[1]],clues[z[0]])
            print(words)

So I'm trying to take the second character from each line in the clues.txt file

A#
M*
N%

Locate that character in the words.txt file

#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*

Then replace it with the first letter from each line in the clues.txt file, so that it's easier for the user to guess the remaining symbol/letter pairings.

Unfortunately, I am receiving the following error message

    Traceback (most recent call last):
      File "<pyshell#5>", line 1, in <module>
        importclues()
      File "/Users/Alastair/Desktop/CA.py", line 70, in importclues
        words.replace(clues[z[1]],clues[z[0]])
    IndexError: string index out of range

Any help would be much appreciated :)

-Alastair

f.read() might not be the right thing to use here... With f.readlines() you get an array with each line as an element.

with f.read() you are reading one big string of characters - not separated at a line break!

clues is a string, so for z in clues puts one character in z .

f = open("words.txt","r")
words = f.read()
f = open("solved.txt","r")
solved = f.read()
f = open("clues.txt","r")
clues = f.readlines()

def importclues():
    global clues
    global words

    for line in clues:
        words.replace(line[1], line[0])
        print(words)

this is untested but should solve the problem. CHanges: read() -> readlines() and the for loop

This code has no error checking - you could for example discard every line where len(line) < 3 (including the newline)

You should use:

clues = f.readlines()

It would take each line and transform in a index for an array. So:

words.replace(z[1], z[0])

Would take you a step forward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM