2015-12-30 77 views
0

我正在製作一個代碼,它從JSON文件中隨機選取信息並將其放入applescript顯示通知中。並且可以通過終端運行JSON文件的問題

我想在我的JSON文件中創建三個不同的列表,它們都鏈接到那裏一件事:random_name,random_sentence,random_sub而不是隻有一個列表,並且只從該列表中選取所有單詞。

我該怎麼做?我應該用字典來做這件事嗎?變量?製作其他JSON文件?

的Python文件:

#!/usr/bin/python 

import json 
import random 
import subprocess 

def randomLine(): 
    jsonfile = "sentences.json" 
    with open(jsonfile) as data_file: 
     data = json.load(data_file) 

    # print len(data) 
    return random.choice(data) 

def executeShell(notif_string, notif_title, notif_subtitle): 
    applescript = 'display notification "%s" with title "%s" subtitle "%s"' % (notif_string, notif_title, notif_subtitle) 
    subprocess.call(["osascript", "-e", applescript]) 

def main(): 
    random_name = randomLine() 
    random_zin = randomLine() 
    random_sub = randomLine() 
    executeShell(random_name, random_zin, random_sub) 

if __name__ == '__main__': 
    main() 

JSON文件:

[ 
    "one", 
    "two", 
    "three", 
    "four", 
    "five", 
    "six" 
] 
+0

嗯,我不明白。您想做什麼?期望的輸出是什麼?你能給我們一個[mcve]嗎? –

+0

使用此代碼,所有字符串都會從JSON文件中的一個列表中選擇隨機單詞,例如「one」,「two」,「three」。我很想在我的JSON文件中有與我的python文件中的字符串鏈接的單獨列表。例如,第一個字符串從列表中隨機選擇單詞「one」,「two」,「three」,第二個字符串從另一個列表中隨機選擇,例如:「aa」,「bb」,「cc」。 – Danisk

回答

0

這應該做的工作。 json.load()返回一個字典,所以你可以只運行random.choice()過它:

import json 
import random 
import subprocess 

jsonfile = "sentences.json" 

def main(): 
    with open(jsonfile, "r") as file: 
     # You might want to add a sanity check here, file might be malformed 
     data = json.load(file) 

    random_name = random.choice(data["name"]) 
    random_zin = random.choice(data["zin"]) 
    random_sub = random.choice(data["sub"]) 
    subprocess.call(["osascript", "-e", "display notification \ 
     '{0}' with title '{1}' \ 
     subtitle '{2}'".format(random_name, random_zin, random_sub)]) 

if __name__ == '__main__': 
    main() 

您的原始JSON文件只包含字符串的一個列表。這裏有3個不同的名單,名爲「名稱」,「鋅」&「子」:

{ 
    "name":[ 
     "one", 
     "two", 
     "three" 
    ], 
    "zin":[ 
     "four", 
     "five", 
     "six" 
    ], 
    "sub":[ 
     "seven", 
     "eight", 
     "nine" 
    ] 
} 
+0

也許你應該注意與原始JSON文件的問題我說你的答案是有用的,你應該注意你的答案與JSON文件 – PyNEwbie

+0

Nevermind的問題。更正後。 – s0r00t

+0

感謝您的答覆!也許我做錯了,但它說:執行錯誤:變量二未定義。你知道我能做些什麼來解決這個問題嗎? @ s0r00t – Danisk