2016-04-15 5 views
-4

私は一般的にPythonでJavascriptコードのビルダーを作ろうとしています。私は考えることができるすべてを試しましたが、私はまだ構文エラーがあります。 エラーは次のとおりです。Python javascript builder

ファイル "test.py"、行12 exploit =( "var word = prompt" "単語を与える"; function pal(){if(word === reverse()。join( '')+ word.split( '')。reverse()。join( '')){document.write( "こんにちはこれは回文文字列です
" + word.split( '') "+ word)と同じです} else {document.write("エラー504(回文ではない)...こんにちはこれは回文ではありません "" + word.split( '')。reverse()。join( '')+ +言葉)}}パル()」と同じではありません ";") ^ にSyntaxError:無効な構文

私は変換するためのものだった( "文字列にJavaScriptコード")ではなく働くアドバイス?おかげで申し訳ありませんもし私の質問の波平明らか

マイコード:あなたはexploitに割り当てるJavaScriptの文字列内の引用符をエスケープする必要があります一つには

import time as t 
from os import path 


def createFile(dest): 

    date=t.localtime(t.time()) 

##Filename=month+date+year 
name="%d_%d_%d.js"%(date[1],date[2],(date[0]%100)) 

exploit = ("var word=prompt("Give a word","");function pal(){if(word===word.split('').reverse().join('')){document.write("hello this is a palindrome<br>"+word.split('').reverse().join('')+" is the same as "+word)}else{document.write("Error 504(Not a palindrome)...hello this is not a palindrome<br>"+word.split('').reverse().join('')+" is not the same as "+word)}}pal();") 

s = str(exploit) 


if not(path.isfile(dest+name)): 
    f=open(dest+name,'w') 
    f.write(s) 
    f.close() 

if __name__=='__main__': 
     createFile("lol") 
     raw_input("done!!!") 
+0

あなたが尋ねていることはまったく明確ではありません。 –

+1

'exploit ='で始まる行の構文ハイライトを見てください。 – Xufox

+0

私はこのすべてを含むfile.jsを作成したい: – javscripters

答えて

0

。代わりに、三重引用符で囲まれた文字列を使うこともできます。これははるかに簡単です。

explioit = '''var word=prompt("Give a word","");function pal(){if(word===word.split('').reverse().join('')){document.write("hello this is a palindrome<br>"+word.split('').reverse().join('')+" is the same as "+word)}else{document.write("Error 504(Not a palindrome)...hello this is not a palindrome<br>"+word.split('').reverse().join('')+" is not the same as "+word)}}pal();''' 

これで問題は解決します。 s = str(exploit) - exploitは既に文字列である必要はありません。

また、関数内でインデントがオフになっているように見えますが、この場合は構文エラーではありませんが、関数が期待通りに機能しません。いくつかのクリーンアップされたコードは次のとおりです。

import time 
from os import path 

def createFile(dest): 
    date = time.localtime() 

    ##Filename=month+date+year 
    name = "%d_%d_%d.js" % (date[1], date[2], (date[0]%100)) 

    exploit = '''var word=prompt("Give a word","");function pal(){if(word===word.split('').reverse().join('')){document.write("hello this is a palindrome<br>"+word.split('').reverse().join('')+" is the same as "+word)}else{document.write("Error 504(Not a palindrome)...hello this is not a palindrome<br>"+word.split('').reverse().join('')+" is not the same as "+word)}}pal();''' 

    if not(path.isfile(dest+name)): 
     with open(dest+name,'w') as f: 
      f.write(exploit) 

if __name__=='__main__': 
    createFile("lol") 
    raw_input("done!!!")