【问题标题】:how to extract words before a particular word using regex in python [closed]如何在python中使用正则表达式提取特定单词之前的单词[关闭]
【发布时间】:2019-04-10 14:16:42
【问题描述】:

我需要提取特定单词之前的单词。

我的数据是。

data="""70MHeAhULOY8KHVLaBwcQHzAAegQICBAF">Similar</a>
</li></ol></div></div></span></div><div class="s"><div> 
 <span class="st">Mail: Consumer Advisory Service, PO Box 
 1673, MELBOURNE <em>VIC</em> 3001. Email: Click here to 
contact us via email. Any personal information you give 
 ;...kJP70MHeAhULOY8KHVLaBwcQIDAKegQIBxAE">Cached  </a>
 </li></ol></div></div></span></div><div class="s"><div> 
 <span class="st">Australia. Consumer Advisory Service 
 GPO Box 
1673. MELBOURNE, <em>VIC</em>, 3001. AUSTRALIA. New Zealand. 
Cadbury Freepost 577. PO Box 890. Dunedin&nbsp;...</span>

我正在尝试提取'VIC'之前的单词

我的预期输出是 ['1673, MELBOURNE','1673. MELBOURNE,'],因为我们的数据中有两个匹配项

我的代码: re.find_all(r"\*+\s(\*) &lt;em&gt; vic",data)

但不工作

【问题讨论】:

  • 你能分享你到目前为止的尝试吗?
  • 更新了我的代码,请检查
  • HTML解析需要使用beautifulsouplib。
  • 不,我正在尝试使用正则表达式提取信息。不需要汤对象
  • 您的所有数据都会采用这种模式Box 1673, MELBOURNE &lt;em&gt;VIC&lt;/em&gt; 3001. 吗?以文本框开头?

标签: python regex match


【解决方案1】:

您可以使用此正则表达式准确提取 VIC 之前的两个单词,

\s+([^\s]+?\s+[^\s]+?)\s*<em>VIC<\/em>

Demo

这是一个相同的python示例代码,

import re
data='70MHeAhULOY8KHVLaBwcQHzAAegQICBAF">Similar</a></li></ol></div></div></span></div><div class="s"><div>  <span class="st">Mail: Consumer Advisory Service, PO Box  1673, MELBOURNE <em>VIC</em> 3001. Email: Click here to contact us via email. Any personal information you give  ;...kJP70MHeAhULOY8KHVLaBwcQIDAKegQIBxAE">Cached  </a> </li></ol></div></div></span></div><div class="s"><div>  <span class="st">Australia. Consumer Advisory Service  GPO Box 1673. MELBOURNE, <em>VIC</em>, 3001. AUSTRALIA. New Zealand. Cadbury Freepost 577. PO Box 890. Dunedin&nbsp;...</span>'
d = re.findall(r"\s+([^\s]+?\s+[^\s]+?)\s*<em>VIC<\/em>",data)
print(d)

这给出了以下输出,

['1673, MELBOURNE', '1673. MELBOURNE,']

【讨论】:

  • 效果不错,如何只提取vic前的一个词
  • 只提取一个词,你可以使用 \s+([^\s]+?)\s*VIC
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 2018-12-03
  • 2021-04-20
  • 2023-03-30
相关资源
最近更新 更多