【发布时间】:2018-07-05 10:38:22
【问题描述】:
我正在使用一个家用工具来解析计算机配置以验证是否应用了某些基本配置,如果没有应用,它会在我运行该工具的主机上的文本文件中生成警报。
该工具不会通过不起作用的计算机制作文件,而是为所有人制作文件。
我想解析这个文本文件并获取每台计算机对应的每个段落,然后发送一封电子邮件给负责计算机的 IT,告诉他他必须做什么。
例如:
---- mycomputerone ----
Hello
During Test of mycomputerone following misconfiguration were detected
- bad ip adress
- bad name
please could take the action to correct it and come back to us?
---- mycomputertwo ----
Hello
During Test of mycomputertwo following misconfiguration were detected
- bad ip adress
- bad name
- administrative share available
please could take the action to correct it and come back to us?
---- mycomputerthree ----
.....
我想获取hello 和? 之间的文本,但不知道该怎么做
我试过了
re.search(r'hello'(S*\w+)\?'), text)
没有用。我通过
读取文件d = open(file, 'r'; encoding="UTF-8")
text = d.read()
【问题讨论】:
-
你尝试过任何模式了吗?你在文件中的阅读情况如何?为什么不逐行读取,检查一行是否以
---开头,然后将后续行添加到当前记录中? -
是的,我试过 re.search(r'hello'(S*\w+)\?'), text)。但它没有用。我通过 d = open(file, 'r'; encoding="UTF-8") text = d.read() 读取文件
-
这可能是个好主意
-
好的,所以你将它作为一个完整的字符串读入。你可以试试
re.findall(r'(?m)^\s*Hello\s*([^?]+)', d),但它很容易受到攻击(如果内容包含?怎么办?)。 -
提示:不要使用正则表达式,逐行解析文本。这真的是基本的文本解析内容,只需要最低限度的编程技能和常识。
标签: python regex python-3.x parsing