![](/img/trans.png)
[英]How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python
[英]Keep last word on each line of text file, delete rest
我編寫了這個python腳本,它在文本文件中的每一行上保留第一個單詞,然后刪除其余的單詞。
我怎么能做相反的,有點意思,保留文件中每一行的最后一個字,並刪除之前的所有單詞和空格?
import sys
with open(sys.argv[1]) as f, open('out.txt', 'w') as out:
for line in f:
out.write(line.split()[0]+'\n')
因此,如果給定文件中的一行“在某處”,所有將被保留並寫入該行的out.txt將是“某處”。
使用line.split()[-1]
來獲取最后一個單詞。
Python支持負索引:
>>> lis = [1, 2, 3, 4, 5]
>>> n = 1
>>> lis[-n]
5
>>> lis[len(lis) - n] # equivalent to lis[-n]
5
你的代碼:
import sys
with open(sys.argv[1]) as f, open('out.txt', 'w') as out:
for line in f:
out.write(line.split()[-1]+'\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.