【发布时间】:2019-12-15 03:15:49
【问题描述】:
我有一个行政档案数据集,其中包括简短的传记。我正在尝试通过使用 python 和一些模式匹配来提取人们的年龄。一些句子的例子是:
- “邦德先生,67 岁,是英国的工程师”
- “Amanda B. Bynes,34 岁,是一名演员”
- “Peter Parker (45) 将成为我们的下一任管理员”
- “Dylan 先生 46 岁。”
- “史蒂夫·琼斯,年龄:32,”
这些是我在数据集中发现的一些模式。我想补充一点,还有其他模式,但我还没有遇到它们,不知道我怎么能做到这一点。我编写了以下代码,效果很好,但效率很低,因此在整个数据集上运行会花费太多时间。
#Create a search list of expressions that might come right before an age instance
age_search_list = [" " + last_name.lower().strip() + ", age ",
" " + clean_sec_last_name.lower().strip() + " age ",
last_name.lower().strip() + " age ",
full_name.lower().strip() + ", age ",
full_name.lower().strip() + ", ",
" " + last_name.lower() + ", ",
" " + last_name.lower().strip() + " \(",
" " + last_name.lower().strip() + " is "]
#for each element in our search list
for element in age_search_list:
print("Searching: ",element)
# retrieve all the instances where we might have an age
for age_biography_instance in re.finditer(element,souptext.lower()):
#extract the next four characters
age_biography_start = int(age_biography_instance.start())
age_instance_start = age_biography_start + len(element)
age_instance_end = age_instance_start + 4
age_string = souptext[age_instance_start:age_instance_end]
#extract what should be the age
potential_age = age_string[:-2]
#extract the next two characters as a security check (i.e. age should be followed by comma, or dot, etc.)
age_security_check = age_string[-2:]
age_security_check_list = [", ",". ",") "," y"]
if age_security_check in age_security_check_list:
print("Potential age instance found for ",full_name,": ",potential_age)
#check that what we extracted is an age, convert it to birth year
try:
potential_age = int(potential_age)
print("Potential age detected: ",potential_age)
if 18 < int(potential_age) < 100:
sec_birth_year = int(filing_year) - int(potential_age)
print("Filing year was: ",filing_year)
print("Estimated birth year for ",clean_sec_full_name,": ",sec_birth_year)
#Now, we save it in the main dataframe
new_sec_parser = pd.DataFrame([[clean_sec_full_name,"0","0",sec_birth_year,""]],columns = ['Name','Male','Female','Birth','Suffix'])
df_sec_parser = pd.concat([df_sec_parser,new_sec_parser])
except ValueError:
print("Problem with extracted age ",potential_age)
我有几个问题:
- 有没有更有效的方法来提取这些信息?
- 我应该改用正则表达式吗?
- 我的文本文档很长,而且我有很多。我可以一次搜索所有项目吗?
- 检测数据集中其他模式的策略是什么?
从数据集中提取的一些句子:
- “2010 年授予 Love 先生的股权奖励占其总薪酬的 48%”
- “George F. Rubin(14)(15) 68 岁受托人,自:1997 年。”
- “INDRA K. NOOYI,56 岁,自 2006 年起担任百事可乐首席执行官 (CEO)”
- “Lovallo 先生,47 岁,于 2011 年被任命为财务主管。”
- “查尔斯·贝克先生,79 岁,是生物技术公司的商业顾问。”
- “Botein 先生,43 岁,自我们成立以来一直是我们董事会的成员。”
【问题讨论】:
-
这些简短的 ppl 传记是否包含除年龄以外的任何数字?
-
是的,他们有。它们包含的财务信息可以是股票数量、金额等。
-
那么,这些其他数字是否具有固定格式,例如货币总是有美元或英镑符号等?
-
是的,这些是 SEC 文件,因此具有格式。唯一不是年龄的两位数字应该是百分比。
-
因此,您的策略应该是在段落中删除所有其他特定格式的数字。那你就只剩下Age了,如果你能提供一个简短的传记例子,我也可以给出代码
标签: python nlp pattern-matching text-mining