python - 在特定字符串开始后查找方括号外的文本

标签 python regex pandas

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

示例数据框:

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 进行类似的循环,但无法获得所需的结果。

感谢您的帮助!

最佳答案

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

[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"]]

关于python - 在特定字符串开始后查找方括号外的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56278717/

相关文章:

python根据子列表值重新排列列表中的元素

python - 如何找到Python中MemoryError的来源?

python - 获取对象名称的问题

python - 在 docker : "ImportError: No module named tqdm" 中运行 python 代码

regex - 使用正则表达式查找和重命名文件/文件夹

regex - 使用 sed 和 mv 重命名文件

正则表达式范围在 0 到 100 之间,包括两位小数

python - 如何按列中的值分组,找到空值,然后替换

python - ValueError : You are trying to merge on datetime64[ns] and object columns. 如果你想继续你应该使用 pd.concat

python - 如何根据 pandas 中前两行的值添加列