I try to translate dates with Python. If "January" is in the string, I replace it with "janvier" etc.
I loop trough the json database. But when there is two months in the same string ("september" and "october"), only the first is translated. Why?
datestring = datestring.replace(" - ", "-")
# Trad french/english
if "January" or "january" in datestring:
x["auction_date"] = datestring.replace("January", "janvier")
if "February" in datestring:
x["auction_date"] = datestring.replace("February", "février")
if "March" in datestring:
x["auction_date"] = datestring.replace("March", "mars")
if "April" in datestring:
x["auction_date"] = datestring.replace("April", "avril")
...
You need to assign the replacement back to the date string, as strings are immutable in Python:
datestring = datestring.replace(" - ", "-")
# Trad french/english
if "January" or "january" in datestring:
datestring = datestring.replace("January", "janvier")
if "February" in datestring:
datestring = datestring.replace("February", "février")
if "March" in datestring:
datestring = datestring.replace("March", "mars")
if "April" in datestring:
datestring = datestring.replace("April", "avril")
# now make the assignment to your data frame
x["auction_date"] = datestring
...
You don't need conditionals in this example. datestring.replace("January", "janvier")
itself is a check. I'd recommend the following.
>>> datestring = "JanUarY"
>>> def english_to_french(month):
... month = month.lower()
... month = month.replace("january", "janvier")
... month = month.replace("february", "février")
... return month
...
>>> x = english_to_french(datestring) >>> print(x)
janvier
This may not be the most efficient, but possibly easier to manage.
Good luck.
PS: Wanted to point out a common oopsy
You have:
# Trad french/english
if "January" or "january" in datestring:
x["auction_date"] = datestring.replace("January", "janvier")
The if
statement in this check doesn't evaluate the way you think it does. Each condition after an and/or
is treated independently. Here is an example.
>>> if "January":
... print(True) ...
True
>>> mystr = "Bobby" >>> if "January" or "january" in mystr: ... print("Bobby will always be in January") ...
Bobby will always be in January
Instead
>>> if "January" in mystr or "january" in mystr:
... print("Bobby will never be in January")
...
>>>
Or best yet!
>>> mystr = "JanUarY"
>>> if "january" in mystr.lower():
... print("We found you!")
...
We found you!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.