【发布时间】:2019-03-26 01:03:33
【问题描述】:
我有一系列来自推文的熊猫文本。这些推文是关于狗的。一些推文包含狗的名字。该名称以下列方式显示。 “...blah blah blah named name。blah blah blah...” 我需要的作品前后的字符数未知。我想提取 name。
我相信我需要使用积极的后向断言和正则表达式的搜索选项。我查看了 re.search 的文档以及以下 SO 问题:How to extract the substring between two markers? 和 Regex captured groups with positive lookbehind (python),以及本教程 https://www.rexegg.com/regex-lookarounds.html。我还是觉得卡住了。
这是我目前的两个想法:
一)
tweet = 'This is a Shotokon Macadamia mix named Cheryl. Sophisticated af.'
m = re.search('(?<=named)[A-Z][a-z]+', tweet)
m.group(0)
B)
s.str.extract(^named([A-Z][a-z])\.$)
根据文档,A) 应该返回“Cheryl”,但我收到一个属性错误:AttributeError: 'NoneType' object has no attribute 'group'。
B) 仅适用于系列,并非推文系列中的每个元素都包含“...命名 name”。结构体。我不确定如何将其合并到代码中,以便返回 Cheryl。
【问题讨论】:
-
如果你使用 pandas,请使用
df['col'].str.extract(r'\bnamed\s+([A-Z][a-z]*)')
标签: python regex string positive-lookahead