用Python把py檔案中的行數刪除掉
阿新 • • 發佈:2019-02-08
可惡的我用福晰閱讀器打開了機器學習電子書,把程式碼複製了下來,準備執行。但是每行程式碼前都有行數。如下:
1 # import the necessary packages 2 from sklearn.preprocessing import LabelBinarizer 3 from sklearn.metrics import classification_report 4 from keras.models import Sequential 5 from keras.layers.core import Dense 6 from keras.optimizers import SGD 7 from keras.datasets import cifar10 8 import matplotlib.pyplot as plt 9 import numpy as np 10 import argparse # construct the argument parse and parse the arguments 17 ap = argparse.ArgumentParser() 18 ap.add_argument("-o", "--output", required=True, 19 help="path to the output loss/accuracy plot") 20 args = vars(ap.parse_args()) # load the training and testing data, scale it into the range [0, 1], 19 # then reshape the design matrix # ...
因此需要把前面的行數刪除掉才可以執行。
上網找到了Python開啟檔案的方法,把檔案內容讀取為str格式,找出有換行符\n的地方,到達空格' '前的數字都刪除掉。
新建一個檔案:RmvLineCnt.py
# -*- coding: cp936 -*- import os as os path1 = "E:\FENG\workspace_python" files= os.listdir(path1) for file in files: #遍歷資料夾 if not os.path.isdir(file): #判斷是否是資料夾,不是資料夾才打開 f = os.path.basename(file) #print "",f #列印結果 #outfile.write(""+f+"\n") #paths="textdata/"+f paths = "E:\FENG\workspace_python\keras_cifar10.py" infile = open(paths,"r") #讀取檔案 text = infile.read() infile.close( ) #print text textBefore = text Index = 0 for i in range(0, len(text)): if i+1 >=len(text): break if (i==0)&(text[i]>='0')&(text[i]<='9'): Index = i while(Index<len(text)): Index = Index + 1 if text[Index]==' ': text = text[Index+1:len(text)] #刪除開頭的數字 break if (text[i] == '\n')&(text[i+1]>='0')&(text[i+1]<='9'): Index = i while(Index<len(text)): Index = Index + 1 if text[Index]==' ': text = text[0:i+1] + text[Index+1:len(text)] #字串拼接 break file_object = open('keras_cifar10.py', 'w') file_object.write(text) file_object.close( )
測試程式碼前記得把keras_cifar10.py原始檔備份一次。再用本程式操作檔案。
程式碼在Xp 32bit ,python 2.7.15測試通過。
結果keras_cifar10.py的檔案變成了以下:
# import the necessary packages from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import classification_report from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import SGD from keras.datasets import cifar10 import matplotlib.pyplot as plt import numpy as np import argparse # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-o", "--output", required=True, help="path to the output loss/accuracy plot") args = vars(ap.parse_args()) # load the training and testing data, scale it into the range [0, 1], # then reshape the design matrix
下次再也不用一行一行的刪除行數了……