2016-04-08 10 views
0

ich ein Anfänger in Python, und ich bin aus einer Datei mit dem Inhalt zu lesen:Formatierung fast eine Json-Datei

{ „Anführungszeichen“: [ "ich Ihre Überlebenschancen ausrechnen konnte, aber du wirst es nicht mögen. "," Ich würde dir Ratschläge geben, aber du würdest nicht hören. Niemand tut es jemals. "," Ich schmerze, also bin ich. "," Ich habe es gesehen. Es ist Unsinn (Über einen Magrathean Sonnenuntergang, den Arthur großartig findet) "," Nicht dass sich jemand dafür interessiert, was ich sage, aber das Restaurant ist am anderen Ende des Universums. "," Ich denke du solltest wissen, dass ich sehr deprimiert bin. "," Meine Fähigkeit zum Glücklichsein ", fügte er hinzu," Sie könnten in eine Streichholzschachtel passen, ohne zuerst die Streichhölzer herauszunehmen. "," Arthur: "Marvin, irgendwelche Ideen?" Marvin: "Ich habe eine Million Ideen. Sie alle weisen auf sicheren Tod hin. \ "", "\" Was ist los? \ "[Fragte Ford] \" Ich weiß es nicht \ ", sagte Marvin, \" ich war noch nie dort. \ "", "Marvin:" Ich bin grob geschätzt dreißig Milliarden mal intelligenter als du. Lassen Sie mich Ihnen ein Beispiel geben. Denk an eine Zahl, eine beliebige Zahl. \ "Zem: \" Er, fünf. \ "Marvin: \" Falsch. Siehst du? "" Zaphod: "Trillian, ich versuche, mit Würde zu sterben. Marvin: \ "Ich versuche nur, um zu sterben. \" "]} *

Wie Sie sehen, es ist fast eine Json-Datei aber mit zusätzlichen Zeichen wie:. [\

Aufgabe : Formiat Inhalt der Datei, so kann ich getrennte Anführungszeichen zugreifen und zufällige Zitate auszudrucken

ich so etwas wie diese

jsonfile = open(INPUT, "r") 
jsonobject = json.load(jsonfile) 
someString = "\n\"{quotes}\"\n".format(quotes=jsonobject["quotes"]) 

, die von loszuwerden versuchen könnte. {Zitate:}. aus dem String Th Es bleiben zusätzliche unerwünschte Zeichen übrig und ich habe versucht, string.replace getrennt und in einer Schleife zu verwenden, aber es gibt mir nicht das Ergebnis, das ich will.

Beispiel: holder = someString.replace("[\]", '')

Nach der Formatierung getan wird Ich glaube, ich eine Schleife verwenden sollte und versuchen, das Zufalls Modul mit random.string?

+1

Eigentlich ... das ist gültig json, das gibt Ihnen ein Diktat mit einer Liste von Zitaten. Zum Beispiel ist 'data [" quotes "] [0]' '' 'Ich könnte Ihre Überlebenschance berechnen, aber Sie werden es nicht mögen. Sie erhalten diese '\ 'Escape-Zeichen, weil die JSON-Strings Strings eingebettet haben. – tdelaney

+0

BTW, es ist toll zu sehen, dass Sie Zitate aus einigen der weltweit größten Literatur haben. – tdelaney

Antwort

4

Sie haben gültige JSON-Daten bereits. \" ist ein Escapezeichen (es ist Teil des Zeichenfolgenwerts) und [...] ist ein JSON Array (analog zu einer Python-Liste).

einfach Ihre Daten als JSON laden:

>>> import json 
>>> jsondata = r'''{"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.\""]}''' 
>>> data = json.loads(jsondata) 
>>> data 
{'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."']} 
>>> from pprint import pprint 
>>> pprint(data) 
{'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."']} 
>>> import random 
>>> print(random.choice(data['quotes'])) 
I've seen it. It's rubbish. (About a Magrathean sunset that Arthur finds magnificent) 
>>> print(random.choice(data['quotes'])) 
I ache, therefore I am. 

In der obigen Demo ich die random.choice() function verwenden eines der Zitate, die zufällig aus der Liste auszuwählen.

Das einzige, was fehlt, ist Marvin Wiegenlied, mein Liebling aller utterings Marvin:

Jetzt hat sich die Welt ins Bett
Dunkelheit nicht meinen Kopf
Ich kann durch Infrarot sehen versenken gegangen
Wie ich die Nacht hassen

Jetzt lege ich mich
versuchen zu schlafen unten Sie elektrische Schafe
Süßer Traum wünscht zählen ke können ep
Wie ich die Nacht hasse

0

Dies sollte funktionieren, wie es ist.

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))]