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