在 Python 3 中使用前瞻推断年龄
Inferring age with lookaheads in Python 3
我有一堆推文和各种元数据,我想出于社会语言学目的对其进行分析。为了做到这一点,我试图根据用户在个人简历中提供的信息等来推断用户的年龄。
为此,我使用正则表达式来匹配用户简历中的几个重复模式,例如用户提到一个数字后跟 "years old" 的各种拼写,如:
"John, 30 years old, engineer."
但是,我还想检查 "years old" 之后的内容,因为很多人提到他们 children 的年龄,我不希望将其错误地关联到用户的年龄年龄,如:
"John, father of a 12 year old kid, engineer"
所以上面这种情况应该忽略,所以我只能保留可以推断有效年龄的用户。
我的程序是这样的:
import csv
import re
with open("test_corpus.csv") as corpus:
corpus_read = csv.reader(corpus, delimiter=",")
for row in corpus_read:
if re.findall(r"\d{2}\s?(?=years old\s?|yo\s?|yr old\s?|y o\s?|yrs old\s?|year old\s?(?!son|daughter|kid|child))",row[5].lower()):
age = re.findall(r"\d{2}\s?",row[5].lower())
for i in age:
print(i)
该程序在某些情况下似乎可以运行,但在我创建的用于试用的小测试文件中,它错误地匹配了字符串 "I have a 12 yo son" 和 returns 12 中提到的年龄匹配的年龄,我不希望这样。我猜这与程序中某些时候的括号或定界符有关,但我花了几个小时在上面,但我在论坛上找不到任何有用的东西,所以任何帮助将不胜感激。
因此,实际问题是:如何让程序根据我已有的程序,不将 "John, father of a 12 year old kid, engineer" 中的 12 识别为用户的年龄?
我在编程方面有些新手,所以如果我忘记提及一些重要的事情,我深表歉意,如果您需要更多详细信息,请随时告诉我。
提前致谢!
好的,经过几天的程序调整,最重要的是,四处询问,我已经能够解决问题了!我无法给出详细的解释,因为我自己不确定是否完全理解它,但问题似乎是代码中空格的位置。但是,如果有人可以提供技术性的和适当的解释,请随时提出。
无论如何,解决办法是:
import csv
import re
with open("test_bio.csv") as corpus:
corpus_read = csv.reader(corpus, delimiter=",")
for row in corpus_read:
if re.search(r"\d{2}\s?(?=(?:years old|yo|yr old|y o|yrs old|year old)(?!\s?son|\s?daughter|\s?kid|\s?child))" ,row[5].lower()):
age2 = re.findall(r"\d{2}\s?",row[5].lower())
for z in age2:
print(z)
再次感谢您的帮助!
我有一堆推文和各种元数据,我想出于社会语言学目的对其进行分析。为了做到这一点,我试图根据用户在个人简历中提供的信息等来推断用户的年龄。 为此,我使用正则表达式来匹配用户简历中的几个重复模式,例如用户提到一个数字后跟 "years old" 的各种拼写,如:
"John, 30 years old, engineer."
但是,我还想检查 "years old" 之后的内容,因为很多人提到他们 children 的年龄,我不希望将其错误地关联到用户的年龄年龄,如:
"John, father of a 12 year old kid, engineer"
所以上面这种情况应该忽略,所以我只能保留可以推断有效年龄的用户。
我的程序是这样的:
import csv
import re
with open("test_corpus.csv") as corpus:
corpus_read = csv.reader(corpus, delimiter=",")
for row in corpus_read:
if re.findall(r"\d{2}\s?(?=years old\s?|yo\s?|yr old\s?|y o\s?|yrs old\s?|year old\s?(?!son|daughter|kid|child))",row[5].lower()):
age = re.findall(r"\d{2}\s?",row[5].lower())
for i in age:
print(i)
该程序在某些情况下似乎可以运行,但在我创建的用于试用的小测试文件中,它错误地匹配了字符串 "I have a 12 yo son" 和 returns 12 中提到的年龄匹配的年龄,我不希望这样。我猜这与程序中某些时候的括号或定界符有关,但我花了几个小时在上面,但我在论坛上找不到任何有用的东西,所以任何帮助将不胜感激。
因此,实际问题是:如何让程序根据我已有的程序,不将 "John, father of a 12 year old kid, engineer" 中的 12 识别为用户的年龄?
我在编程方面有些新手,所以如果我忘记提及一些重要的事情,我深表歉意,如果您需要更多详细信息,请随时告诉我。
提前致谢!
好的,经过几天的程序调整,最重要的是,四处询问,我已经能够解决问题了!我无法给出详细的解释,因为我自己不确定是否完全理解它,但问题似乎是代码中空格的位置。但是,如果有人可以提供技术性的和适当的解释,请随时提出。
无论如何,解决办法是:
import csv
import re
with open("test_bio.csv") as corpus:
corpus_read = csv.reader(corpus, delimiter=",")
for row in corpus_read:
if re.search(r"\d{2}\s?(?=(?:years old|yo|yr old|y o|yrs old|year old)(?!\s?son|\s?daughter|\s?kid|\s?child))" ,row[5].lower()):
age2 = re.findall(r"\d{2}\s?",row[5].lower())
for z in age2:
print(z)
再次感谢您的帮助!