如何在Python中以优雅(简洁)的方式计算列表上的n次笛卡尔积,即A \xc3\x97 ... \xc3\x97 A(n次)?
\n例子:
\n>>> l = ["a", "b", "c"]\n>>> cart_prod(l, 0)\n[]\n>>> cart_prod(l, 1)\n[(\'a\',), (\'b\',), (\'c\',)]\n>>> cart_prod(l, 2)\n[(\'a\', \'a\'), (\'a\', \'b\'), (\'a\', \'c\'), (\'b\', \'a\'), (\'b\', \'b\'), (\'b\', \'c\'), (\'c\', \'a\'), (\'c\', \'b\'), (\'c\', \'c\')]\n>>> cart_prod(l, 3)\n[(\'a\', \'a\', \'a\'), (\'a\', \'a\', \'b\'), (\'a\', \'a\', \'c\'), (\'a\', \'b\', \'a\'), (\'a\', \'b\', \'b\'), (\'a\', \'b\', \'c\'), (\'a\', \'c\', \'a\'), (\'a\', \'c\', \'b\'), (\'a\', \'c\', \'c\'),\n (\'b\', \'a\', \'a\'), (\'b\', \'a\', \'b\'), (\'b\', \'a\', \'c\'), (\'b\', \'b\', \'a\'), (\'b\', …Run Code Online (Sandbox Code Playgroud) 在Python(3.5.0)中,我想在屏幕或文件中打印一个包含igigunicode符号(更准确地说是从Wiktionary以JSON格式检索的IPA符号)的字符串到屏幕或文件中,例如
print("\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n")
Run Code Online (Sandbox Code Playgroud)
正确打印
?w??t??m?l?n
Run Code Online (Sandbox Code Playgroud)
-但是,每当我在变量中使用字符串时,例如
ipa = '\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n'
print(ipa)
Run Code Online (Sandbox Code Playgroud)
它只是按原样打印出字符串,即
\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n
Run Code Online (Sandbox Code Playgroud)
这没有太大帮助。
我尝试了几种避免这种情况的方法(例如通过deocde/ encode),但是没有一种方法可以帮助您。
我不能合作
u'\u02c8w\u0254\u02d0t\u0259\u02ccm\u025bl\u0259n'
Run Code Online (Sandbox Code Playgroud)
要么因为我已经将字符串作为变量检索(作为正则表达式匹配的结果),而且在我的代码中没有任何地方输入实际的文字。
也可能是我在从JSON结果进行转换的过程中犯了一个错误;到目前为止,我已经使用将该字节流转换为字符串str(f.read()),通过正则表达式提取了IPA部分(并在双反斜杠上进行了替换)并将其存储在字符串变量中。
编辑:
这是我到目前为止的代码:
def getIPAen(word):
url = "https://en.wiktionary.org/w/api.php?action=query&titles=" + word + "&prop=revisions&rvprop=content&format=json"
jsoncont = str((urllib.request.urlopen(url)).read())
jsonmatch = re.search("\{IPA\|/(.*?)/\|", jsoncont).group(1)
#print("jsomatch: " + jsonmatch)
ipa = jsonmatch.replace("\\\\", "\\")
#print("ipa: " + ipa)
print(ipa)
Run Code Online (Sandbox Code Playgroud)
修改后json.loads:
def getIPAen(word):
url = "https://en.wiktionary.org/w/api.php?action=query&titles=" + word + "&prop=revisions&rvprop=content&format=json"
jsoncont = str((urllib.request.urlopen(url)).read())
jsonmatch = re.search("\{IPA\|/(.*?)/\|", jsoncont).group(1)
#print("jsonmatch: " + jsonmatch)
jsonstr = "\"" …Run Code Online (Sandbox Code Playgroud)