我必须编写一个程序来反转文件中单词的字母。
例如,如果文件包含单词:
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()函数的情况下编辑主函数以反转单词的顺序?
答案 0 :(得分:6)
with open('path/to/input') as infile:
words = []
for line in infile:
words.append(line.strip()[::-1])
with open('path/to/output', 'w') as outfile:
for word in words[::-1]:
outfile.write(word)
outfile.write('\n')
一个衬里(因为我们都喜欢它们):
with open('path/to/input') as infile:
words = [line.strip()[::-1] for line in infile]
with open('path/to/output', 'w') as outfile:
outfile.write('\n'.join(words[::-1]))
答案 1 :(得分:0)
reversey = lambda w: w if len(w) < 2 else reversey(w[1:]) + w[0]
>>> reversey("yellow")
reversex = labda x: x if len(x) < 2 else reversex(x[1:]) + [w[0]]
>>>reversex(["yellow","apple","purple","watermelon"])
是一个递归实现...但是有很多方法可以做到这一点...我写了这个函数,你的老师会知道你可能没有写它...但希望你xcan看看我是什么做并将其改为你教授期望的东西
答案 2 :(得分:0)
如果你组合rev | tac
(如你的情况那样),那么结果就是一个反向字节顺序的文件(忽略空格中可能存在的差异)。要获得所需的输出,您可以从最后一个字节开始读取并一次移动到文件的开头一个字节。
你可以一次读/写:
with open('words.txt', 'rb') as file, open('reverse.txt', 'wb') as outfile:
outfile.write(file.read()[::-1])
一次一个字节:
#!/usr/bin/env python
"""Print file in the reverse byte order."""
import os
with open('words.txt', 'rb') as file, open('reverse.txt', 'wb') as outfile:
file.seek(0, os.SEEK_END) # move to the end
for position in range(file.tell() - 1, -1, -1): # from last position
file.seek(position, os.SEEK_SET) # move back
outfile.write(file.read(1)) # read/write byte
缺点是Python中一次读取一个字节的速度很慢。优点是它还支持不适合内存的文件。
mmap
module allows to treat a file as a string:
#!/usr/bin/env python3
from mmap import ACCESS_READ, mmap
with open('words.txt') as f, mmap(f.fileno(), 0, access=ACCESS_READ) as s:
with open('reverse.txt', 'wb') as outfile:
for i in range(len(s) - 1, -1, -1):
outfile.write(s[i:i+1])
您还可以阅读一个区块。请参阅Most efficient way to search the last x lines of a file in python。