Home > Back-end >  how would I fix my code inorder to create a file of words in this format(see body)?
how would I fix my code inorder to create a file of words in this format(see body)?

Time:12-04

see if the word can be read backwards and is also a word in the file. If the word is, save the word in the list. After you go through each of the words, sort the list, print out/write the word paired with its read-backwards word to a new file.

the format that should be the final outcome

this is my code so far and i was wondering if anyone could help me?

f = open('C:\\Users\\Owner\\OneDrive\\Documents\\RandomWords.txt')
words = f.readlines() #creats list and gets rid of whitespace
for i in range(len(words)):
    words[i] = words[i].strip()

f.close()

f2 = open('C:\\Users\\Owner\\OneDrive\\Documents\\finaloutput.txt', 'w')

for j in words:
    temp = j.lower()[::-1] #reads backwards
    if j.capitalize() in words:
        f2.write('{}--{}\n'.format(words[i], temp))
f2.close()

ok so this is my updated code and I need help sorting it and getting rid of repeated words in the new written file named Target.txt.

This is part of the file Target.txt and there are repeat words father down but I cant fit it in the pic

f = open('C:\\Users\\Owner\\OneDrive\\Documents\\RandomWords.txt')
words = f.readlines() #creats list and gets rid of whitespace

list1 = []

for i in range(len(words)):
    words[i] = words[i].strip()
    list1.append(words[i])

f.close()

f2 = open('C:\\Users\\Owner\\OneDrive\\Documents\\Target.txt', 'w')


for j in words:
    temp = j.lower()[::-1] #reads backwards
    if temp.capitalize() in list1:
        list1.remove(temp.capitalize())
        f2.write('{}--{}\n'.format(j, temp.capitalize()))
f2.close()

CodePudding user response:

Your code was right you were just using the wrong variable when putting it back in the final words.

f = open('C:\\Users\\Owner\\OneDrive\\Documents\\RandomWords.txt')
words = f.readlines() #creats list and gets rid of whitespace
for i in range(len(words)):
    words[i] = words[i].strip()

f.close()

f2 = open('C:\\Users\\Owner\\OneDrive\\Documents\\finaloutput.txt', 'w')

for j in words:
    print('yes')
    temp = j.lower()[::-1] #reads backwards
    if temp.capitalize() in words:
        print('uwu')
        f2.write('{}--{}\n'.format(j, temp))
f2.close()

you also used j instead of temp in your if statement. because you used words[i] when writing it to the file it would only write the last item in the random words file. and because you used the j variable instead of temp it wasn't flipped and therefore didn't work.

  • Related