2016-04-15 29 views
-4

我正在嘗試爲Python代碼編寫一般的Python生成器。我試過所有我能想到的,但我仍然有語法錯誤。 錯誤是這樣的:Python的JavaScript生成器

文件「test.py」,第12行 exploit =(「var word = prompt(」Give a word「,」「); function pal(){if(word === word.split('')。reverse()。join('')){document.write(「hello this is a palindrome
」+ word.split('')。reverse()。join('')+ 「和」+「一樣)} else else {document.write(」Error 504(Not a palindrome)... hello this is not a palindrome
「+ word.split('')。reverse()。join ')+「與」+「不一樣)}}} pal();」) ^ SyntaxError:invalid syntax

我是將(「JavaScript代碼」)轉換爲字符串工作建議?謝謝,對不起,如果我的問題wasnt明確

我的代碼:

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

一件事,你需要逃避,你是分配給exploit的JavaScript字符串中的引號。或者,您可以使用三重引號的字符串,這很容易:

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!!!")