【发布时间】:2021-12-18 23:35:06
【问题描述】:
我正在编写一个 python 脚本来查找名称属性并将其添加到任何具有标签的 html 文件中。 到目前为止,我有这样的事情:
lfiles = glob.glob('*.html')
chars = []
for arq in lfiles:
#Resets all counters for a new file
x = 0
fullfile = []
insertname = ''
insertpos = 0
addname = False
with open(arq , 'r') as f:
while 1:
char = f.read(1) #reads character by character
if not char:
break
fullfile.append(char) #adds to the full stream to be saved later
if char == '<':
appending = True
if appending:
chars.append(char)
if ''.join(chars) == '<button ':
insertpos = x #This should get the correct position to insert the name attr
addname = True
if char == '>' and appending:
appending = False
chars = []
if addname:
fullfile = fullfile[:insertpos]+[' name="inputname" ']+fullfile[insertpos:]
addname = False
x = x+1
print(''.join(fullfile))
脚本没有优化,可能做了太多不必要的处理,但它确实有效。大多数文件都有这样的内容:
<button type="button"
class="btn btn-primary btn-xs"
ng-click="$ctrl.showFilters()"
ng-show="!$ctrl.filters">
<i class="fa fa-filter" aria-hidden="true"></i> Filters
</button>
<button type="button"
class="btn btn-primary btn-xs"
ng-click="$ctrl.hideFilters()"
ng-show="$ctrl.filters">
运行后,输出是这样的:
<button name="inputname" type="button" --OK!
class="btn btn-primary btn-xs"
ng-click="$ctrl.showFilters()"
ng-show="!$ctrl.filters">
<i class="fa fa-filter" aria-hidden="true"></i> Filters
</button>
<butto name="inputname" n type="button" --Wrong position!
class="btn btn-primary btn-xs"
ng-click="$ctrl.hideFilters()"
ng-show="$ctrl.filters">
我很难理解为什么这个职位有时是正确的
【问题讨论】:
标签: python-3.x string replace