如何根据姓名和生日的CSV文件找到谁的下一个生日?



我们得到了一个包含姓名和生日的CSV文件,我们必须在函数中输出下一个生日。

一直收到本地未绑定的错误,不知道如何修复,基本上是尝试读取文件,检查日期,找到下一个日期,然后返回与该日期相关的名称

birthdates.csv:
Draven Brock,01/21/1952
​Easton Mclean,09/02/1954
​Destiny Pacheco,10/10/1958
​Ariella Wood,12/20/1961
​Keely Sanders,08/03/1985
​Bryan Sloan,04/06/1986
​Shannon Brewer,05/11/1986
​Julianne Farrell,01/29/2000
​Makhi Weeks,03/20/2000
​Lucian Fields,08/02/2010
Function Call:
​nextBirthdate("birthdates.csv", "01/01/2022")
Output:
​Draven Brock
def nextBirthdate(filename, date):
f = open(filename, 'r')
lines = f.readlines()
f.close()
for i in range(len(lines)):
lines[i] = lines[i].strip()
# split for the target date
date = line.split('/')
month = date[0]
day = date[1]
diff = 365
diffDays = 0
bName = None

bDays = []
for line in lines:
items = line.split(",")
names = items[0]
# split the date apart between month, day, and year
bDay = items[1].split("/")
bDays.append(bDay)
for d in bDays:
if bDay[0] == month:
if bDay[1] > day:
diffDays = int(bDay[0]) - int(day)
if diffdays < diff:
diff = diffDays
bName = name
elif bDay[0] > month:
diffDays = ((int(bDay[0]) - 1) * 31) + int(day)
if diffDays < diff:
diff = diffDays
bName = name
if bName == None:
return nextBirthdate(filename, "01/01/2022")
return bName
if __name__ == "__main__":
filename = "birthdates.csv"
date = "12/31/2022"
print(nextBirthdate(filename, date))

欢迎使用堆栈溢出。这样做的方法是

  1. 读取CSV数据

  2. 将数据转换为例如pandas DataFrame

    2a。我建议你将日期转换为例如pd.Timestamp,不要将它们作为字符串保存,以避免在比较时发生不好的事情

  3. 根据日期对DataFrame进行排序,或者找到具有最小值的行,这取决于

如何做每一件事都是它自己的问题,至少有一个答案已经在堆栈溢出和其他地方了,所以你可能不需要问一个新的,只需要搜索它。

所以我得到了这个-你只想知道下一天是谁,并想要基于CSV文件的人的name。以下代码应工作

import pandas as pd
from datetime import date
def nextBirthdate(file, inp_date):
d,m,y = [int(x) for x in inp_date.split('/')]
df = pd.read_csv('file.csv', header=None)
df[1] = pd.to_datetime(df[1])
df[1] = df[1].apply(lambda x: x.replace(year=y))
inp_date = date(y,m,d)
df['Diff'] = (df[1].dt.date - inp_date).dt.days
return df.sort_values(by=['Diff'])[0].values[0]
nextBirthdate("birthdates.csv", "01/01/2022")

相关内容

  • 没有找到相关文章

最新更新