用Python把py文件中的行数删除掉

可恶的我用福晰阅读器打开了机器学习电子书,把代码复制了下来,准备运行。但是每行代码前都有行数。如下:

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

下次再也不用一行一行的删除行数了……

猜你喜欢

转载自blog.csdn.net/qq_27158179/article/details/82883971
今日推荐