2 回答

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可能最終希望在數(shù)據(jù)框中使用它,因?yàn)槟鷮⑵錁?biāo)記為 pandas(請(qǐng)參閱Andrej 的回答),但無(wú)論哪種方式,您都可以使用內(nèi)插法從字符串中解析日期:
fr"(?i)((?:{months}) *\d{{4}}) *(?:-|–) *(present|(?:{months}) *\d{{4}})"
{months}所有可能的月份名稱(chēng)和縮寫(xiě)的交替組在哪里。
import calendar
import re
from datetime import datetime
from dateutil.relativedelta import relativedelta
text = """Wipro Limited | Hyderabad, IN Dec 2017 – Present
Project Analyst
Infosys | Delhi, IN Apr 2017 – Nov 2017
Software Developer
HCL Technologies | Hyderabad, IN Jun 2016 – Mar 2017
Software Engineer
"""
def parse_date(x, fmts=("%b %Y", "%B %Y")):
for fmt in fmts:
try:
return datetime.strptime(x, fmt)
except ValueError:
pass
months = "|".join(calendar.month_abbr[1:] + calendar.month_name[1:])
pattern = fr"(?i)((?:{months}) *\d{{4}}) *(?:-|–) *(present|(?:{months}) *\d{{4}})"
total_experience = None
for start, end in re.findall(pattern, text):
if end.lower() == "present":
today = datetime.today()
end = f"{calendar.month_abbr[today.month]} {today.year}"
duration = relativedelta(parse_date(end), parse_date(start))
if total_experience:
total_experience += duration
else:
total_experience = duration
print(f"{start}-{end} ({duration.years} years, {duration.months} months)")
if total_experience:
print(f"total experience: {total_experience.years} years, {total_experience.months} months")
else:
print("couldn't parse text")
輸出:
Dec 2017-May 2020 (2 years, 5 months)
Apr 2017-Nov 2017 (0 years, 7 months)
Jun 2016-Mar 2017 (0 years, 9 months)
total experience: 3 years, 9 months

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
import re
import numpy as np
import pandas as pd
text = '''Wipro Limited | Hyderabad, IN Dec 2017 – Present
Project Analyst
Infosys | Delhi, IN Apr 2017 – Nov 2017
Software Developer
HCL Technologies | Hyderabad, IN Jun 2016 – Mar 2017
Software Engineer
'''
def pretty_format(monthts):
return f'{monthts/12:.1f} years' if monthts > 11 else f'{monthts:.1f} months'
data = []
for employer, d1, d2 in re.findall(r'(.*?)\s*\|.*([A-Z][a-z]{2} [12]\d{3}) – (?:([A-Z][a-z]{2} [12]\d{3})|Present)', text):
data.append({'Employer': employer, 'Begin': d1, 'End': d2 or np.nan})
df = pd.DataFrame(data)
df['Begin'] = pd.to_datetime(df['Begin'])
df['End'] = pd.to_datetime(df['End'])
df['Experience'] = ((df['End'].fillna(pd.to_datetime('now')) - df['Begin']) / np.timedelta64(1, 'M')).apply(pretty_format)
print(df)
total = np.sum(df['End'].fillna(pd.to_datetime('now')) - df['Begin']) / np.timedelta64(1, 'M')
print()
print(f'Total experience = {pretty_format(total)}')
印刷:
Employer Begin End Experience
0 Wipro Limited 2017-12-01 NaT 2.5 years
1 Infosys 2017-04-01 2017-11-01 7.0 months
2 HCL Technologies 2016-06-01 2017-03-01 9.0 months
Total experience = 3.8 years
添加回答
舉報(bào)