簡體   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