我有这样的列表列表,我给你举例输入:
thislist= [[1, 'Aug 2014, Sept 2016, Ian 2014, Feb 2016', 2], [5,'Aug 2015, Sept 2012, Ian 2015, Aug 2017',4]]
我有兴趣只为索引[1]处理每个列表(带有日期的列表),我想要的输出将是:
thislist= [[1, 'Ian, Aug 2014; Feb, Sept 2016', 2], [5,'Sept 2012; Ian, Aug 2015; Aug 2017',4]]
(上面它只是一个例子,在我的实际情况中,我将有更多的日期与年,但格式完全相同) 基本上我想订购每个日期名称缩写(它们是罗马尼亚语,但它们在英语上是完全相同的)从日历(例如:Ian,Feb,Mar,Apr ...等)的实际订单,并将它们分组为按时间顺序排列的年份(2010年,2011年,2012年,2013年等)的例子,并且有#34 ;;"分离。我怎么能这样做?我认为唯一的选择应该是正则表达式,但我对它不是很好,所以我可以得到我想要的输出?我正在使用python 3,非常感谢您的时间!
答案 0 :(得分:0)
您应该考虑“%B%Y”它需要整月的名称,因为罗马尼亚语和英语月份缩写在所有情况下都不相同
from datetime import datetime
thislist = [[1, 'August 2014, September 2016, January 2014, February 2016', 2],
[5, 'August 2015, September 2012, January 2015, February 2017', 4]]
sorted_list = []
months = []
i = 0
for dates in thislist:
sorted_list = []
chgDates = dates[1].split(",")
for test1 in chgDates:
sorted_list.append(test1.strip())
test = sorted(sorted_list, key=lambda x: datetime.strptime(x, "%B %Y"))
str1 = ', '.join(test)
thislist[i][1] = str1.replace(",", ";")
i = + 1
print(thislist)
响应:
[[1, 'January 2014; August 2014; February 2016; September 2016', 2], [5, 'September 2012; January 2015; August 2015; February 2017', 4]]
答案 1 :(得分:0)
现在您可以翻译英语 - >罗马尼亚。你应该阅读一下python中的列表和字典。如果你只是等待社区,我不会认为你会收到完整的答案。
from datetime import datetime
import re
thislist = [[1, 'August 2014, September 2016, January 2014, February 2016, March 2016', 2],
[5, 'August 2015, September 2012, January 2015, February 2017', 4]]
sorted_list = []
months = []
i = 0
def translateInRo(string, dyct):
substrs = sorted(dyct, key=len, reverse=True)
regexp = re.compile('|'.join(map(re.escape, substrs)))
return regexp.sub(lambda match: dyct[match.group(0)], string)
for dates in thislist:
sorted_list = []
chgDates = dates[1].split(",")
for test1 in chgDates:
sorted_list.append(test1.strip())
test = sorted(sorted_list, key=lambda x: datetime.strptime(x, "%B %Y"))
str1 = ', '.join(test)
translate = translateInRo(
str1, {"September": "Septembrie", "January": "Ianuarie", "September": "Septembrie", "February": "Februarie", "March": "Martie"})
thislist[i][1] = translate
i = + 1
print(thislist)