Python文本解析并保存为html

时间:2016-08-02 11:01:34

标签: python html loops

我一直在玩Python试图编写脚本来扫描目录中的特定文件,查找某些关键字并将这些关键字出现的行保存到新文件中。我想出了这个;

import sys, os, glob

for filename in glob.glob("./*.LOG"):
 with open(filename) as logFile:
 name = os.path.splitext(logFile.name)[0]
 newLOG = open(name + '_ERROR!'+'.LOG', "w")
 allLines = logFile.readlines()
 logFile.close()
 printList = []

 for line in allLines:
    if ('ERROR' in line) or ('error' in line):
     printList.append(line)

 for item in printList:
     # print item    
     newLOG.write(item)

这一切都很好,但我想我会尝试保存这个新文件,因为html将其全部包含在权限标签(html,head,body ......)中,这样我可以更改关键字的字体颜色。到目前为止它看起来像这样;

import sys, os, glob

for filename in glob.glob("./*.LOG"):

 with open (filename) as logFile:
     name = os.path.splitext(logFile.name)[0]
     newLOG = open(name + '_ERROR!'+'.html', "w")
     newLOG.write('<html>')
     newLOG.write('<head>')
     newLOG.write('<body><p>')

     allLines = logFile.readlines()
     logFile.close()
     printList = []

     for line in allLines:
        if ('ERROR' in line) or ('error' in line):
         printList.append(line)

     for item in printList:
         # print item 

        newLOG.write('</html>')
        newLOG.write('</head>')
        newLOG.write('</body><p>')   
        newLOG.write(item)

现在问题是我是新手,我还在试图弄清楚如何使用缩进和循环。因为我的html标签是从循环中追加的,所以每一行都有{{1 },<html>&amp; <head>标记了它们,它看起来不对劲。我理解这个问题,并尝试重写事物,以便标签在循环外部应用,但我没有取得多大成功。

有人能告诉我一个更好的方法来获取当前文件的文件名,创建一个新文件+附加它,因为我认为这就是为什么我在尝试改变它的工作方式时会遇到文件处理错误的原因。

由于

1 个答案:

答案 0 :(得分:1)

这是将线条缩进到合适水平的问题。 HTML页脚必须打印在标题行的缩进级别,而不是在循环内缩进。试试这个:

import sys, os, glob
import cgi

for filename in glob.glob("./*.LOG"):

    name = os.path.splitext(filename)[0]
    with open(filename, 'r') as logFile, open('%s_ERROR!.html' % name, 'w') as outfile:
        outfile.write("<html>\n<head>\n</head>\n<body><p>")

        allLines = logFile.readlines()
        printList = []

        for line in allLines:
            if ('ERROR' in line) or ('error' in line):
                printList.append(line)

        for item in printList:
            # Note: HTML-escape value of item
            outfile.write(cgi.escape(item) + '<br>')

        outfile.write("</p></body>\n</html>")   

请注意,您不需要使用printList - 您可以在浏览日志时发出HTML代码。

考虑将其分解为更小的函数以实现可重用性和可读性。

相关问题