Python javascript构建

2024-10-02 16:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用Python为Javascript代码创建一个生成器。我已经想尽办法了,但还是有语法错误。 错误如下:

“文件”测试.py“,第12行 利用漏洞=(“var word=prompt”(“Give a word”,“”);函数pal(){if(word===文字分割(“”).reverse().join(“”)){文档.写入(“你好,这是回文
”+文字分割(“”).reverse().join(“”)+与“+word)}else相同{文档.写入(“错误504(不是回文)…您好这不是回文
”+文字分割(“”).reverse().join(“”)+“不是与“+word)}}pal();”相同) ^ 语法错误:无效语法

我想把(“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!!!")

Tags: 代码namedateifisaswordwrite
1条回答
网友
1楼 · 发布于 2024-10-02 16:24:36

首先,您需要转义指定给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!!!")

相关问题 更多 >