所以我试图解决Python问题。 我有一个文本文件,最后是单词和Sybol。但秩序错了。 为了解决这个问题,我需要一个脚本:
现在我尝试了一些东西,但它的所有东西都比我预期的要长得多,所以我很好奇你们可以考虑什么样的方法。
先谢谢
PS:
我将附上一个示例文本文件将如何显示在这里:
!
cake +
house -
wood *
barn /
shelf =
town
目标是在完成的文件中它看起来像这样:
cake !
house +
wood -
barn *
shelf /
town =
答案 0 :(得分:1)
您可以使用tempfile.NamedTemporaryFile
写信给shutil.move
,将原始文件替换为更新后的内容:
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))
答案 1 :(得分:-1)
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)