【问题标题】:Getting the right position to write in a text stream获得在文本流中写入的正确位置
【发布时间】: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


    【解决方案1】:

    你不知道吗,我在写问题时就发现了问题。那么,问题是什么?嗯,差不多就是这样:

    fullfile = fullfile[:insertpos]+[' name="inputname" ']+fullfile[insertpos:]
    

    这意味着完整文件的长度现在增加了 1。所以,不是 10,而是 11。我没有设置偏移量,所以,每次我添加名称时,我都会偏离 +1。如果它运行 5 次,我最终会得到 &lt;b name="inputname" utton ...&gt; 这是修复:

    if addname:
        fullfile = fullfile[:insertpos]+[' name="inputname" ']+fullfile[insertpos:]
        addname = False
        x = x + 1 #The magic fix!
    

    现在,我的实际用例有[' name="',insertname,'" ']。这意味着现在偏移量为 3,因为该数组由 3 个元素组成,所以长度增加了 3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      相关资源
      最近更新 更多