在特定字符串的开头之后在方括号之外查找文本

时间:2019-05-23 15:38:03

标签: python regex pandas

我正在尝试在[名称]的特定字符串之后的方括号之外找到文本。然后,我将在DataFrame中为个人的“名称”创建一个新列。信息字段的顺序可以更改,因此,例如,我无法调用[名称]和[年龄]之间的文本。

示例DataFrame:

Info = {'Information': ["[Name] Tom [Age] 22 [Height] 6'2","[Age] 21 [Name] Ben [Height] 6'0","[Age] 20 [Name] Mike [Height] 6'3"]}

df = DataFrame(Info,columns= ['Information'])

这是我尝试过的代码:

Name = []
for i in range(0,len(df)):
   start = 'Name]'
   end = '\['
   s = df["Information"].iloc[i]
   Name.append(s[s.find(start)+len(start):s.rfind(end)])
df["Name"] = Name

我在新创建的名称列中收到的输出是:

[" Tom [Age] 22 [Height] 6'", " Ben [Height] 6'", "  Mike [Height] 6'"]

但是我希望输出为:

["Tom", "Ben", "Mike"]

我也尝试过使用Regex进行类似的循环,但无法获得所需的结果。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

df['Name']=df['Information'].str.extract(r'\[Name\] (\w*)')

答案 1 :(得分:1)

这是使用str.extract的一种方式:

df['Name'] = df.Information.str.extract(r'(?<=\[Name\])\s((?:\s*\w+)+)')

print(df)
              Information              Name
0   [Name] Tom [Age] 22 [Height] 6'2   Tom
1   [Age] 21 [Name] Ben [Height] 6'0   Ben
2  [Age] 20 [Name] Mike [Height] 6'3  Mike

答案 2 :(得分:1)

您还可以使用split和列表理解来提取数据:

[s.split("[Name]",1)[-1].split("[")[0].strip() for s in Info["Information"]]

# ['Tom', 'Ben', 'Mike']

编辑

我用其他方法进行了一些测试,但它们都花费了大约相同的时间(列表中有300万个项目):

使用split():1.47秒

[s.split("[Name]",1)[-1].split("[",1)[0].strip() for s in Info["Information"]]

使用已编译的正则表达式:1.49秒

import re
findName = re.compile(r".*\[Name\] (.+?) \[.*")
[findName.match(s).group(1) for s in Info["Information"]]

使用index()函数:1.41秒

[s[i+7:s.index(" [",i)] for s in Info["Information"] for i in [s.index("[Name] ")] ]

避免split()方法中的strip():1.27秒

[s.split("[Name] ",1)[-1].split(" [",1)[0] for s in Info["Information"]]