我是Python初学者,正在阅读一个包含以下内容的文件:
{"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.\""]}*
正如您所看到的,它几乎是一个json文件,但是有一些额外的字符,比如:[\。你知道吗
任务:格式化文件内容,以便我可以访问单独的引号并打印随机引号。你知道吗
我可以试试这样的
jsonfile = open(INPUT, "r")
jsonobject = json.load(jsonfile)
someString = "\n\"{quotes}\"\n".format(quotes=jsonobject["quotes"])
它将从字符串中去掉{quotes:}。虽然还保留了其他不需要的字符,我也尝试过单独使用string.replace
并在循环中使用,但它并没有给出我想要的结果。你知道吗
例如:holder = someString.replace("[\]", '')
格式化完成后,我想我应该使用一个循环并尝试使用random.string
的随机模块?你知道吗
这应该按原样工作。你知道吗
您已经有了有效的JSON数据。
\"
是转义引号(因此它是字符串值的一部分),而[...]
是JSON数组(类似于Python列表)。你知道吗只需将数据加载为JSON:
在上面的演示中,我使用^{} function 从列表中随机选取一个引号。你知道吗
唯一缺少的是马文的摇篮曲,这是我最喜欢的马文的话语:
相关问题 更多 >
编程相关推荐