这是输入的mylist示例:
mylist = [['RWILY MORSHED', 7670315350025, 'August/2014, Iulie/2014, Septembrie/2014', 1620, 1620], ['AL BADRI MOHAMMED YAHYA TAWFEEQ', 7700119350028, 'Martie/2015, Aprilie/2015, Februarie/2015', 1620, 1620]]
我想要的输出是这样的:
mylist = [['RWILY MORSHED', 7670315350025, 'August 2014, July 2014, September 2014', 1620, 1620], ['AL BADRI MOHAMMED YAHYA TAWFEEQ', 7700119350028, 'March 2015, April 2015, February 2015', 1620, 1620]]
基本上我想将月份名称从罗马尼亚语转换为英语并获得上述所需的输出(我需要在输出中的相同索引2位置的所有月份!)
为此,我最终得到了这个:
conversionsEnNames = {"Ianuarie": "January", "Februarie": "February","Martie": "March", "Aprilie": "April","Mai": "May","Iunie": "June", "Iulie": "July","August": "August", "Septembrie": "September","Octombrie": "October", "Noiembrie": "November","Decembrie": "December"}
for i in mylist:
i[2]=i[2].replace("/", " ")
for j in i:
if j in conversionsEnNames:
j = conversionsEnNames[j]
i[2]=j
print(mylist)
但是会打印出来:
[['RWILY MORSHED', 7670315350025, 'August 2014, Iulie 2014, Septembrie 2014', 1620, 1620], ['AL BADRI MOHAMMED YAHYA TAWFEEQ', 7700119350028, 'Martie 2015, Aprilie 2015, Februarie 2015', 1620, 1620]]
自从2014年Iulie'以来,地图一定无法运作。 !=' Iulie'所以它可以将它转换为7月,我要修改什么才能实现我的不良输出?非常感谢你的时间!
答案 0 :(得分:2)
应该这样做。
for item in mylist:
item[2] = item[2].replace('/', ' ')
for roman, english in conversionsEnNames.items():
item[2] = item[2].replace(roman, english)
答案 1 :(得分:1)
你也可以使用正则表达式(因为正则表达式很酷,不是因为解决方案比其他解决方案更好)。这是一个片段,用于处理单个字符串中的替换:
import re
def rep(m):
if m.group(1) in conversionEnNames:
return conversionEnNames[m.group(1)] + " " + m.group(2)
else:
return m.group(0)
test = "blah blah Iulie/2014 blah Februarie/2015 blih blah bluh"
result = re.sub(r"([A-Za-z]+)/(\d\d\d\d)", rep, test)
它应该产生
"blah blah July 2014 blah February 2015 blih blah bluh"
您可以根据需要改进。
答案 2 :(得分:1)
你可以使用简单的字典查找
def convert_date(date_string, conversionsEnNames):
parts = [part.split('/') for part in date_string.split(', ')]
return ', '. join(conversionsEnNames[part[0]] + ' ' + part[1] for part in parts)
for line in mylist:
line[2] = convert_date(line[2], conversionsEnNames)
mylist
[['RWILY MORSHED', 7670315350025, 'August 2014, July 2014, September 2014', 1620, 1620],
['AL BADRI MOHAMMED YAHYA TAWFEEQ', 7700119350028, 'March 2015, April 2015, February 2015', 1620, 1620]]
答案 3 :(得分:0)
只需更改循环中的最后三行。
>>> for i in mylist:
... i[2]=i[2].replace("/", " ")
... for j in conversionsEnNames:
... i[2] = i[2].replace(j, conversionsEnNames[j])
...
>>> print(mylist)
[['RWILY MORSHED', 7670315350025, 'August 2014, July 2014, September 2014', 1620, 1620], ['AL BADRI MOHAMMED YAHYA TAWFEEQ', 7700119350028, 'March 2015, April 2015, February 2015', 1620, 1620]]
答案 4 :(得分:0)
小心:i
不是"月"字符串,但整个列表。
因此"Iulie"
不属于列表(但是是列表中元素的子字符串)。
此外,您可以对.replace(x, conversionsEnNames[x])
中的每个x
使用conversionsEnNames
:这不是"安全" (为什么?),但在这种情况下它可以工作。