为什么在对wxPython运行mki18n.py时会出现'非命名参数警告'?

4 投票
1 回答
1865 浏览
提问于 2025-04-18 04:59

我在运行我的Python代码中的 mki18n.py 脚本时,遇到了一个警告,警告出现在这一行:

 >>> dlg = wx.MessageDialog(None, str (_("Attached device is \"%s\",\nschedule file header is for \"%s\"") % (rt_model, line)), _("Device mismatch"), wx.OK | wx.ICON_ERROR)

然后出现了这个:

warning: 'msgid' format string with unnamed arguments cannot be properly localized:
         The translator cannot reorder the arguments.
         Please consider using a format string with named arguments,
         and a mapping instead of a tuple for the arguments.

mki18n.py 脚本不喜欢连续出现的两个 s%,但我无法理解这个警告信息的意思。否则(如果我不考虑国际化直接运行我的程序),就没有错误,而且那个对话框总是能正常显示。

那一行有什么问题呢?(有什么可以改进的地方?)

编辑 通过使用 geni18n.py(以及它的相关文件来自i18nwxapp包),我得到了预期的结果,没有错误(也就是生成了用于翻译的 .pot 文件)。不过我还是不清楚我的代码中是否有问题是 geni18n 可以容忍的,还是 mki18n 有问题,是因为我特定的那行代码引发的?

1 个回答

9

简单来说,这段话的意思是,如果翻译者需要调整变量的顺序,他们会遇到困难。我们来看下面的例子:

my_string = "Hello %s, it is %s o'clock." % ('Foo', 'two')

现在假设翻译者需要先用 two,然后再用 Foo

translated_string = "It is %s o'clock, Mr. %s" % ('Foo', 'two')

如果不使用 带命名参数的格式字符串,那么 Foo 还是会放到第一个 %s 里,这样就会得到:

print translated_string
# Output: It is Foo o'clock, Mr. two.

要解决这个问题,只需使用 命名参数。所以上面的例子可以改成:

my_string = "Hello %(person)s, it is %(time)s o'clock." % ({
    'person':'Foo', 
    'time':'two'
})

translated_string = "It is %(time)s o'clock, Mr. %(person)s" % ({
    'person':'Foo', 
    'time':'two'
})

这样,翻译者就可以随意把 persontime 放到他们想要的位置。而且,这样也能让他们知道这些变量的意思,如果你只用 %s,他们就不知道了。

希望这样能让事情更清楚。

撰写回答