Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串拆分为多个字符串_Python - Fatal编程技术网

Python 将字符串拆分为多个字符串

Python 将字符串拆分为多个字符串,python,Python,我的知识很有限,但我正在尽力 我想把一个字符串拆分成多个字符串,变量 现在,由于以下原因,我使用了http服务器脚本: 我只是稍微修改了一下,我收到了一个POST字符串解码,我想把这个字符串拆分成不同的字符串或变量 这是完整的代码: #!/usr/bin/env python """ Very simple HTTP server in python. Usage:: ./dummy-web-server.py [<port>] Send a GET request::

我的知识很有限,但我正在尽力

我想把一个字符串拆分成多个字符串,变量

现在,由于以下原因,我使用了http服务器脚本:

我只是稍微修改了一下,我收到了一个POST字符串解码,我想把这个字符串拆分成不同的字符串或变量

这是完整的代码:

#!/usr/bin/env python
"""
Very simple HTTP server in python.
Usage::
    ./dummy-web-server.py [<port>]
Send a GET request::
    curl http://localhost
Send a HEAD request::
    curl -I http://localhost
Send a POST request::
    curl -d "foo=bar&bin=baz" http://localhost
"""
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import sys
import time
import csv
import urllib
import psycopg2


con = None

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write("<html><body><h1>hi!</h1></body></html>")

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
    # Doesn't do anything with posted data
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself
        print post_data # <-- Print post data
        self._set_headers()
        dataEncoded = str(post_data)
        dataString = urllib.unquote(post_data)
        timeString = str(time.strftime("%d %m %Y %H:%M:%S"))
        with open("decoded_log.csv",'a') as resultFile:
            wr = csv.writer(resultFile, dialect='excel')
            wr.writerow([dataString,timeString])
        with open("encoded_log.csv",'a') as resultFile:
            wr = csv.writer(resultFile, dialect='excel')
            wr.writerow([dataEncoded,timeString])    
        con = psycopg2.connect("host=localhost dbname=data_log user=USER password=PASSWORD")
        print "DB Connection successful."
        cur = con.cursor()
        cur.execute("INSERT INTO log(data,date_time) VALUES (%s, %s)",(dataString,timeString))
        con.commit()           

def run(server_class=HTTPServer, handler_class=S, port=5400):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting httpd...'
    httpd.serve_forever()

if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

sys.exit()
#/usr/bin/env python
"""
python中非常简单的HTTP服务器。
用法::
./dummy-web-server.py[]
发送GET请求::
卷曲http://localhost
发送HEAD请求::
curl-Ihttp://localhost
发送POST请求::
旋度-d“foo=bar&bin=baz”http://localhost
"""
从BaseHTTPServer导入BaseHTTPRequestHandler,HTTPServer
导入SocketServer
导入系统
导入时间
导入csv
导入URL库
导入psycopg2
con=无
类S(BaseHTTPRequestHandler):
def_设置_标题(自):
自我发送_响应(200)
self.send_标题('Content-type','text/html')
self.end_头()
def do_获得(自我):
self.\u set\u headers()
self.wfile.write(“嗨!”)
def do_头(自身):
self.\u set\u headers()
def do_POST(自我):
#不处理已发布的数据

content_length=int(self.headers['content-length'])#用正则表达式提取单词,然后像这样分割字符串:

import re

s1 = """\"\"\"\"C3643\"\"\"\"32303138\"\",\"\"|\"\"=\"="""
print s1

s2 = re.findall(r'\w+', s1)
print s2

a = s2[0]
s3 = s2[1]

b,c,d = s3[:2], s3[2:5], s3[5:]
print a
print b
print c
print d
输出:

""""C3643""""32303138"",""|""="=
['C3643', '32303138']
C3643
32
303
138

对于我们这些人来说,你觉得正则表达式难以理解:

>>> post="%22%22%22%5B001%5D%22%22%3A%22%22C3643%22%22%2C%22%22%7C%5B002%5D%22%22%3A%22%2232303138%22%22%2C%22%22%7C%22%22%3D%22="
>>> result= urllib.unquote(post).replace('"',"").split(',')
>>> a = result[0].split(':')[1]
>>> b = result[1].split(':')[1][:2]
>>> c = result[1].split(':')[1][2:5]
>>> d = result[1].split(':')[1][5:]
>>> a,b,c,d
('C3643', '32', '303', '138')
>>> a
'C3643'
>>> b
'32'
>>> c
'303'
>>> d
'138'

非常感谢MYGz!有一件事我没有提到,那就是绳子。s1=“”C3643”“32303138”“”|“=”本例中的第一个数字C3643长度可变,但始终位于第一个“内部”,本例中的第二个数字32303138的长度相同。所以第一个数字我会完整地取下,下一个数字我会把它分成更多的数字。那些
必须被转义,我的坏。幸运的是它有偶数个
,所以它连在一起了。给我一秒钟。我会改正的it@Bannedillo现在请检查一下。BnNeDILO如果它解决了你的问题,请考虑一下,谢谢你的帮助,但是它给了我这个错误,model = DATASTION(1)。拆分(':')[1 ] [:2 ]索引错误:列表索引超出这个范围。例如,这个帖子:% 22% 2200% 3A0A9% 3A59D68 16%,22% 22% 22% 2232303138% 22% 22,因为这个字符串被解码为<代码>“00:0a9:59d6816”“32303138”“
并且不遵循您最初发布的格式。如果len(result)<2:print“data error”