【发布时间】:2019-04-10 02:19:00
【问题描述】:
我正在使用 python 2.7 在一段文本中查找文本。 以下文字是我摘录的一部分:
Item 1 for Product A: Flour
Solution 1 for Product A: Water
Items 2 for Product B: Milk
Solution 2 for Product B: Oil
Item 3 for Product C: Onions
Method
我有以下 Python 代码来提取我想要的特定信息:
extract = re.findall(r"(?<=Item|s\s).*(?=\sSolution)", page_content)
虽然这会提取一些信息,但我无法提取我需要的所有信息。 我需要包含“项目”这个词,但我无法提取最后一个项目,因为下一个词不是“解决方案”而是方法。
我想要的输出是:
Item 1 for Product A: Flour
Items 2 for Product B: Milk
Item 3 for Product C: Onions
在改进正则表达式方面的任何帮助将不胜感激。
谢谢
【问题讨论】:
-
每行末尾是否总是有换行符?
-
不一定。实际上,当我使用 Python 库将 PDF 转换为文本时,输出文本会连接换行符,因此原始文本实际上是:产品 A 的项目 1:产品 A 的 FlourSolution 1:水等。
标签: python regex regex-lookarounds regex-group