[英]python - read text file, manipulate order
所以我試圖用 Python 解決一個問題。 我有一個文本文件,最后有文字和 Sybol。 但是命令是錯誤的。 為了修復它,我需要一個腳本:
現在我嘗試了一些東西,但一切都比我預期的要長得多,所以我很好奇你們能想到什么樣的方法。
提前致謝
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.