-2

我必须编写一个程序来反转文件中单词的字母。

例如,如果文件包含以下词语:

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() 函数的情况下编辑主函数以反转单词的顺序?

4

3 回答 3

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]))
于 2013-12-09T02:17:46.520 回答
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"])

是一个递归实现......但是有很多方法可以做到这一点......我写了这个函数,你的老师会知道你可能没有写它......但希望你能看看我在做什么并改变它变成了你教授对你的期望

于 2013-12-09T02:19:56.500 回答
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模块允许将文件视为字符串

#!/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])

您也可以一次读取一个块。请参阅在 python 中搜索文件最后 x 行的最有效方法

于 2013-12-09T03:16:02.170 回答