每個月我都會運行一個腳本,根據Excel表的輸入進行一系列的計算。然而,上傳者對月份的拼寫方式并不一致。7月/7月,9月/9月,等等。因此,我目前的解決方案很容易出錯:
excel = pd.read_excel(f'{月} {年} 月報表.xlsx'/span>)
在Python應用程式中,用戶提供的輸入是數字,我在想,我可以用不同的變化在一個字典中進行轉換。
##user input。
while True:
month = int(8) #user input :.
if月 not in(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)。)
print("這不是一個有效的月份。記住要把它打成數字。例如,一月=1")
else:
print("Thank you for giving me the month")
break(span class="hljs-string">"謝謝你給我這個月")
##月的翻譯dict。
month_dict = {1: ["Jan", "January"] 。
2: ["Feb", "2月"]。
8: ["Aug", "Aug"],
9: ["Sep", "Sept", "Sept"]}。
我所嘗試的是:
##it should loop over the various way to type out the month and go with the version that does not throw an error:
excel = pd.read_excel(f'{month_dict[month]} {year} Monthly Statement.xlsx' )
##but does not work since I am not sure how to loop over the different items in the dict.
我怎樣才能做到這一點?
編輯。 檔案名是:1月 2021月報表.xlsx
8月 2021 月結單.xlsx
9月 2021月報表.xlsx
uj5u.com熱心網友回復:
如果月份名稱可能只是縮短了,但我們可以安全地假設它的拼寫是正確的,并且檔案名與你的例子一樣,那么這應該是可行的:
month_dict = {1: "Jan"。
2: "Feb"。
8: "8月"。
9: "Sep"}。
myfile = glob.glob(f'{month_dict[month]}* {year} Monthly Statement.xlsx')
excel = pd.read_excel(myfile[0] )
詳細來說,month-dict[month]當month為3時,我們得到了 "Mar",所以我們要尋找一個名為 "Mar*2021月報表.xlsx "的檔案。這將匹配 "Mar"、"Marc"、"March",甚至不幸的是 "Marchxx",但不匹配 "Ma"(這是一件好事,因為我們不知道應該選擇三月還是五月)或 "Mrch"(這就不太妙了...)
我現在是這樣解決的,但它不像@gimix的回復那樣精簡
##user input。
while True:
month = int(8) #user input :.
if月 not in(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)。)
print("這不是一個有效的月份。記住要把它打成數字。例如,一月=1")
else:
print("Thank you for giving me the month")
break(span class="hljs-string">"謝謝你給我這個月")
##dict
month_dict = {1: ["Jan", "January"] 。
2: ["Feb", "2月"]。
3: ["Mar", "March"] 。
4: ["4月", "4月"],
5: ["May"]。
6: ["Jun", "June"] 。
7: ["July", "July"],
8: ["Aug", "Aug"],
9: ["Sep", "Sept", "9月"],
10: ["Oct", "10月"],
11: ["Nov", "十一月"],
12: ["Dec", "December"]}.
##loop ##loop?
for i in month_dict:
try:
ex = pd.read_excel(f'{month_dict[month][i]} 2021 Monthly Statement.xlsx'/span>)
break
except IOError:
print("error"/span>)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311640.html
標籤:
下一篇:Pandas:匯入有多個作業表的xlsx,在每個df中添加列,并標明其所屬作業表的名稱,將有相同列數的df連接起來。
