我必须编写一个程序来反转文件中单词的字母。
例如,如果文件包含以下词语:
snow
tree
star
wreath
它会将它们更改为:
wons
eert
rats
htaerw
完成后,我必须编写一个新文件,该文件将以相反的顺序写入它们,因此它看起来像:
htaerw
rats
eert
wons
这是我的代码:
def reverse(string):
#empty list for string
word = []
#for each letter in the string obtain the corresponding opposite number
#first letter to last letter, second letter to second last letter, etc...
for letter in range(len(string)-1, -1, -1):
word.append(string[letter])
#create main() function
def main():
#open file and read words in each line
input_file = open("words.txt", "r")
word_file = input_file.readlines()
#empty list for the words in the file, after their letters have been reversed
reversed_list = []
for word in range(len(word_file)):
reverse_word = reverse(word_file[word])
reversed_list.append(reverse_word)
#create new file of the reversed words IN REVERSED ORDER!
reverse_file = open("reverse.txt","w")
reverse_file.writelines(reversed_list)
reverse_file.close()
main()
如何在不使用内置 .reverse() 函数的情况下编辑主函数以反转单词的顺序?