繁体   English   中英

python - 读取文本文件,操作顺序

[英]python - read text file, manipulate order

所以我试图用 Python 解决一个问题。 我有一个文本文件,最后有文字和 Sybol。 但是命令是错误的。 为了修复它,我需要一个脚本:

  • 从上到下逐行读取文本文件
  • 从每一行中取出最后一个字符,即使该行只有 1 个字符,并将他放在下一行,就在最后一个字符之前。 (因为当它跳转到下一行,并将这一行移动到最后一个字符时,上一行的最后一个字符将是这一行新的最后一个字符)
  • 最后将所有内容写入一个新的文本文件

现在我尝试了一些东西,但一切都比我预期的要长得多,所以我很好奇你们能想到什么样的方法。

提前致谢

PS:

我将附上一个示例,文本文件将如何显示在这里:

!
cake    +
house   -
wood    *
barn    /
shelf   =
town

目标是在完成的文件中它看起来像这样:

cake    !
house   +
wood    -
barn    *
shelf   /
town    =

您可以使用shutil.move写入tempfile.NamedTemporaryFile以使用更新的内容替换原始文件:

from tempfile import NamedTemporaryFile
from shutil import move

with open("in.txt") as f, NamedTemporaryFile("w",dir=".",delete=False) as temp:
    # get first symbol
    sym = next(f).rstrip()
    for line in f:
        # split into word and symbol
        spl = line.rsplit(None, 1)
        # write current word followed by previous symbol
        temp.write("{} {}\n".format(spl[0],sym))
        # update sym to point to current symbol
        sym = spl[-1]
# replace original file
move(temp.name,"in.txt")

in.txt之后:

cake !
house +
wood -
barn *
shelf /
town =

如果你想要制表符分隔使用temp.write("{}\\t{}\\n".format(spl[0],sym))

with open('input.txt') as f:
    #this method automatically removes newlines for you
    data = f.read().splitlines()

char, sym = [], []
for line in data:
    #this will work assuming you never have more than one word per line
    for ch in line.split():
        if ch.isalpha():
            char.append(ch)
        else:
            sym.append(ch)

#zip the values together and add a tab between the word and symbol          
data = '\n'.join(['\t'.join(x) for x in zip(char, sym)])

with open('output.txt', 'w') as f:
    f.write(data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM