如何在左侧的2个分隔符和Python右侧的7个分隔符之间隔离文本?

时间:2015-06-22 20:23:25

标签: python regex string split

我有一个字符串:

string = ""7807161604","Sat Jan 16 00:00:57 +0000 2010","Global focus begins tonight. Pretty interested to hear more about it.","Madison Alabama","al","17428434","81","51","Sun Nov 16 21:46:24 +0000 2008","243"

我只想要文字:"全球焦点今晚开始。非常有兴趣了解更多关于它的信息。"" ,它位于第2个和第3个逗号/分隔符之间。 如果我使用:

i = string.split(',', 2)
s = i[2]
j = s.split(',',-7)
print j[0]

我将获得所需的输出。 但是,如果原始字符串之间有一个额外的逗号,如下所示:

string = ""7807161604","Sat Jan 16 00:00:57 +0000 2010","Global focus begins tonight. Pretty interested, to hear more about it.","Madison Alabama","al","17428434","81","51","Sun Nov 16 21:46:24 +0000 2008","243""

然后这种方法不起作用,因为我需要的输出被拆分。任何人都可以帮助并建议一种不同的方法或建议我是否出错?谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用python的内置import serial import time import datetime import MySQLdb serial = serial.Serial("/dev/ttyUSB0", baudrate=9600) db = MySQLdb.connect("localhost", "root", "", "skripsi") cur = db.cursor() code = '' while True: data = serial.read() if data == '\r': print(code) localtime = time.localtime(time.time()) day = localtime.tm_wday time = localtime.tm_hour print day print time cond1 = "SELECT nama_dosen FROM dosen WHERE kode_dosen = '%s'" %code cur.execute(cond1) hitung = cur.rowcount res1 = cur.fetchall() for row in res1: nama_dosen = row[0] if hitung == 1: res1 = nama_dosen elif hitung != 1: print "Dosen tidak Terdaftar" code = '' else: code = code + data 模块来执行此操作。

csv

现在j = next(csv.reader([string])); 是由j分隔的每个项目,如果值包含在,中,则会包含逗号。请参阅"