简体   繁体   中英

python - read text file, manipulate order

so im trying to solve a Problem with Python. Ive got a Text file With words and a Sybol at the end. But the Order is wrong. In order to fix it i would need a Script that :

  • read the text file line by line from Top to Bottom
  • takes the last Char from each line, even if there is only 1 Char at that line, and places him in the Next line, just before the last Char. (because when it jumps to the Next line, and moves this lines last char, the last Char from the previous line will be this lines new last char)
  • and finally write that all to a new text file

Now ive tryed some stuff but its all gotten far longer then i expected, so im curious what kind of approaches you guys can think about.

Thanks in Advance

PS:

i will attach a example how the text files gonna look here :

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

the goal is that in the finished file it looks like this :

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

You can write to a tempfile.NamedTemporaryFile using shutil.move to replace the original file with the updated content:

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 after:

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

If you want tab delimited use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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