<p>我是Python初学者,正在阅读一个包含以下内容的文件:</p>
<blockquote>
<p>{"quotes":["I could calculate your chance of survival, but you won't like it.","I'd give you advice, but you wouldn't listen. No one ever does.","I ache, therefore I am.","I've seen it. It's rubbish. (About a Magrathean sunset that Arthur finds magnificent)","Not that anyone cares what I say, but the Restaurant is on the other end of the universe.","I think you ought to know I'm feeling very depressed.","My capacity for happiness,\" he added, \"you could fit into a matchbox without taking out the matches first.","Arthur: \"Marvin, any ideas?\" Marvin: \"I have a million ideas. They all point to certain death.\"","\"What's up?\" [asked Ford.] \"I don't know,\" said Marvin, \"I've never been there.\"","Marvin: \"I am at a rough estimate thirty billion times more intelligent than you. Let me give you an example. Think of a number, any number.\" Zem: \"Er, five.\" Marvin: \"Wrong. You see?\"","Zaphod: \"Can it Trillian, I'm trying to die with dignity. Marvin: \"I'm just trying to die.\""]}*</p>
</blockquote>
<p>正如您所看到的,它几乎是一个json文件,但是有一些额外的字符,比如:[\。你知道吗</p>
<p><strong>任务</strong>:格式化文件内容,以便我可以访问单独的引号并打印随机引号。你知道吗</p>
<p>我可以试试这样的</p>
<pre><code>jsonfile = open(INPUT, "r")
jsonobject = json.load(jsonfile)
someString = "\n\"{quotes}\"\n".format(quotes=jsonobject["quotes"])
</code></pre>
<p>它将从字符串中去掉{quotes:}。虽然还保留了其他不需要的字符,我也尝试过单独使用<code>string.replace</code>并在循环中使用,但它并没有给出我想要的结果。你知道吗</p>
<p>例如:<code>holder = someString.replace("[\]", '')</code></p>
<p>格式化完成后,我想我应该使用一个循环并尝试使用<code>random.string</code>的随机模块?你知道吗</p>
<p>这应该按原样工作。你知道吗</p>
<pre><code>import json
import random
file = open(<path to your file>,'r')
i = json.load(file)
#print a random quote
print i['quotes'][int(random.randrange(0,len(i['quotes'])-1))]
</code></pre>