1

嗨,我想从 html 表单获取输入并将其传递给我的 python 脚本并使其执行,然后我想在不使用任何框架的情况下在浏览器中打印我的结果。下面是我的python代码:

import re

hap=['amused','beaming','blissful','blithe','cheerful','cheery','delighted']

sad=['upset','out','sorry','not in mood','down']

sad_count=0

happy_count=0

str1=raw_input("Enter Message...\n")

happy_count=len(filter(lambda x:x in str1,hap)) 

sad_count=len(filter(lambda x:x in str1,sad))

if(happy_count>sad_count):

        print("Hey buddy...your mood is HAPPY :-)")

elif(sad_count>happy_count):

            print("Ouch! Your Mood is Sad :-(")

elif(happy_count==sad_count):

        if(happy_count>0 and sad_count>0):

            print("oops! You are in CONFUSED mood :o")

        else:
            print("Sorry,No mood found :>")
4

2 回答 2

4

似乎您使用的是 python3,但在带有 BaseHTTPServer 的 python 2.7(即 python3 中的 HTTP.server)中,您可以执行类似的操作

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write("""
            <html><head></head>
            <body>
            <form method="POST">
            your mood:
            <textarea name="mood">
            </textarea>
            <input type="submit" name="submit" value="submit">
            </form>
            </body>
            </html>
            """)
        return

    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile, 
            headers=self.headers,
            environ={'REQUEST_METHOD':'POST',
                     'CONTENT_TYPE':self.headers['Content-Type'],
                     })
        themood = form["mood"]
        hap=['amused','beaming','blissful','blithe','cheerful','cheery','delighted']
        sad=['upset','out','sorry','not in mood','down']
        sad_count=0
        happy_count=0
        happy_count=len(filter(lambda x:x in themood.value,hap)) 
        sad_count=len(filter(lambda x:x in themood.value,sad))
        if(happy_count>sad_count):
            self.wfile.write("Hey buddy...your mood is HAPPY :-)")
        elif(sad_count>happy_count):
            self.wfile.write("Ouch! Your Mood is Sad :-(")
        elif(happy_count==sad_count):
            if(happy_count>0 and sad_count>0):
                self.wfile.write("oops! You are in CONFUSED mood :o")
            else:
                self.wfile.write("Sorry,No mood found :>")
        return
server = HTTPServer(('', 8181), Handler)
server.serve_forever()

我希望这可以帮助你

于 2013-08-23T12:23:39.900 回答
0

如果你想在本地机器上测试它,你可以用 python 创建一个简单的网络服务器。你可以在这里找到一个很好的教程。您可以编写 python 脚本来处理数据。或者你应该安装一个真正的网络服务器,比如 Apache 或 NGinx,并使用 cgi 或 wsgi 扩展。第二种方法的优点是,在这种情况下,服务器可以处理 html、css、图像等文件,因此您可以专注于您的 python 代码,而无需编写整个现有应用程序。

于 2013-08-23T12:28:50.407 回答