我将如何修复我的代码以创建这种格式的单词文件(见正文)?

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

看看这个词能不能反读,也是文件中的一个词。如果单词是,则将该单词保存在列表中。遍历每个单词后,对列表进行排序,将 out/write 单词与其向后读取的单词配对打印到新文件中。

the format that should be the final outcome

这是我到目前为止的代码,我想知道是否有人可以帮助我?

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()

好的,这是我更新的代码,我需要帮助对其进行排序并删除名为 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()

你的代码是正确的,你只是在把它放回最后的话时使用了错误的变量。

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()

您还在 if 语句中使用了 j 而不是 temp。 因为你在将它写入文件时使用了 words[i] 它只会写入随机单词文件中的最后一项。并且因为您使用了 j 变量而不是 temp 它没有被翻转,因此不起作用。