【问题标题】:python parsing a file and extract paragraphspython解析文件并提取段落
【发布时间】: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


【解决方案1】:

你要求的是

re.findall(r'(?m)^\s*Hello\s*[^?]+', d)

其中d 是作为单个字符串读入的整个文件。见this demo。它有点脆弱,因为如果内容包含?,它将无法正常工作。

我建议逐行阅读,检查一行是否以--- 开头,然后将后续行添加到当前记录中。

见下面Python demo

items = []
tmp = ''
with open(file, 'r'; encoding="UTF-8") as d:
for line in d:
    if (line.strip().startswith('---')):
        if tmp:
            items.append(tmp.strip())
            tmp = ''
    else:
        tmp = tmp + line + "\n"
if tmp:
    items.append(tmp)

print(items)    

输出:

['Hello\n\n During Test of mycomputerone following misconfiguration were detected\n - bad ip adress\n - bad name\n\n please could take the action to correct it and come back to us?', 
 'Hello\n\n During Test of mycomputertwo following misconfiguration were detected\n - bad ip adress\n - bad name\n - administrative share available\n\n please could take the action to correct it and come back to us?']

【讨论】:

  • 如果文件不以'---'结尾,这将丢失最后一条记录。
  • @brunodesthuilliers 我添加了if tmp: items.append(tmp),以便将“尾部”附加到items 列表中。
  • 非常感谢您提供的 2 个解决方案。我会用第二个
猜你喜欢
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多