2016-04-15 52 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!!!")