1

我正在编写一个程序来获取和编辑维基百科上的文章,但在处理前缀为 \u 的 Unicode 字符时遇到了一些麻烦。我已经尝试过 .encode("utf8") ,但它似乎并没有在这里奏效。如何正确编码以 \u 为前缀的这些值以发布到维基百科?请参阅此编辑以了解我的问题。这是一些代码: 获取页面:

url = "http://en.wikipedia.org/w/api.php?action=query&format=json&titles="+urllib.quote(name)+"&prop=revisions&rvprop=content"
articleContent = ClientCookie.urlopen(url).read().split('"*":"')[1].split('"}')[0].replace("\\n", "\n").decode("utf-8")

在我发布页面之前:

data = dict([(key, value.encode('utf8')) for key, value in data.iteritems()])
data["text"] = data["text"].replace("\\", "")
editInfo = urllib2.Request("http://en.wikipedia.org/w/api.php", urllib.urlencode(data))
4

1 回答 1

2

您正在下载 JSON 数据而不对其进行解码。为此使用json

import json

articleContent = ClientCookie.urlopen(url)
data = json.load(articleContent)

JSON 编码的数据看起来很像 Python,它也使用\u转义,但它实际上是 JavaScript 的一个子集。

data变量现在拥有一个深度数据结构。从字符串拆分来看,你想要这件作品:

articleContent = data['query']['pages'].values()[0]['revisions'][0]['*']

现在articleContent 是一个实际的unicode()实例;这是您要查找的页面的修订文本:

>>> print u'\n'.join(data['query']['pages'].values()[0]['revisions'][0]['*'].splitlines()[:20])
{{For|the game|100 Bullets (video game)}}
{{GOCEeffort}}
{{italic title}}
{{Supercbbox  <!--Wikipedia:WikiProject Comics-->
| title =100 Bullets
| image =100Bullets vol1.jpg
| caption = Cover to ''100 Bullets'' vol. 1 "First Shot, Last Call". Cover art by Dave Johnson.
| schedule = Monthly
| format =
|complete=y
|Crime       = y
| publisher = [[Vertigo (DC Comics)|Vertigo]]
| date = August [[1999 in comics|1999]] – April [[2009 in comics|2009]]
| issues = 100
| main_char_team = [[Agent Graves]] <br/> [[Mr. Shepherd]] <br/> The Minutemen <br/> [[List of characters in 100 Bullets#Dizzy Cordova (also known as "The Girl")|Dizzy Cordova]] <br/> [[List of characters in 100 Bullets#Loop Hughes (also known as "The Boy")|Loop Hughes]]
| writers = [[Brian Azzarello]]
| artists = [[Eduardo Risso]]<br>Dave Johnson
| pencillers =
| inkers =
| colorists = Grant Goleash<br>[[Patricia Mulvihill]]
于 2013-01-13T21:57:26.333 回答