我正在尝试查找 [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/