python list items & convert language codes to names

i have a list of languages in my data store for a country which is stored like this :

[u"[u'fa-AF'", u" u'ps'", u" u'uz-AF'", u" u'tk']"]

i want the output as:

fa-AF, ps, uz-AF, tk

or

fa-AF - ps, uz-AF - tk

i have tried a couple of things but have not succeeded yet. seems like the data that has been imported to the datastore was not imported properly. Any help Regarding this would be greatly appreciated.

Also, i would like your suggestions on how to display the language name with these codes.

for example if we have "en-US" then we would like to display it as English (United States) (Note: we do not have the language names stored in the datastore.)


a = [u"[u'fa-AF'", u" u'ps'", u" u'uz-AF'", u" u'tk']"]

Looks like a simple split of the original string. You can re-build the string or strip individual elements:

import ast
codes = [ast.literal_eval(x.strip('[] ')).encode() for x in a]

or

codes = [elem.encode() for elem in ast.literal_eval(','.join(a))]

both return:

['fa-AF', 'ps', 'uz-AF', 'tk']

The names of the languages could be stored in a dictionary, such as:

lang = {'fa-AF': 'farsi-Afghanistan', ... }

and called with

for code in codes:
    print lang[code]

or you can have a look at the Babel library.

链接地址: http://www.djcxy.com/p/57534.html

上一篇: 从他们的知识产权获取访问国家

下一篇: python列出项目并将语言代码转换为名称