繁体   English   中英

Python文本解析并另存为html

[英]Python text parsing and saving as html

我一直在使用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标签是从循环内追加的,所以每一行都有<html><head><body><p>标记在它们周围,这看起来是错误的。 我了解问题所在,并尝试重写内容,以便将标签应用到循环之外,但我没有取得太大的成功。

有人可以告诉我一种更好的方法来获取当前文件的文件名,创建一个新文件并附加它,因为我认为这就是为什么在尝试更改所有文件的工作方式时出现文件处理错误。

谢谢

只是将线条缩到正确的水平。 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代码。

考虑将其分解为较小的功能,以提高可重用性和可读性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM