在Python中从字符串提取未知子串
我有一个这样的字符串:
HTTP/1.1 200 OK
CACHE-CONTROL: max-age=100
EXT:
LOCATION: string to be extracted followed by a \n
SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1
ST: urn:schemas-upnp-org:device:basic:1
USN: uuid:2f402f80-da50-11e1-9b23-0017881892ca
我想提取出在 LOCATION:
后面到换行符之间的内容。
我不能用 substring in string
方法,因为在 'LOCATION:' 后面的内容可能会变化。
我试着把这个字符串变成一个字典,然后获取 'LOCATION' 这个键的值。但这样似乎浪费了内存和处理时间,因为除了那个值,字典对我来说没有用处。而且如果字符串太大,字典的大小可能会大幅增加。
有没有其他方法可以提取 'LOCATION:' 后面到 '\n' 之间的内容呢?
4 个回答
2
你需要用的是 string.index(character) 这个方法:
mystr="HTTP/1.1 200 OK\nCACHE-CONTROL: max-age=100\nEXT:\nLOCATION: string to be extracted followed by a \nSERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1\nST: urn:schemas-upnp-org:device:basic:1\nUSN: uuid:2f402f80-da50-11e1-9b23-0017881892ca"
search = "LOCATION"
start = mystr.index(search)+len(search)
stop = mystr.index("\n", start)
print mystr [ start : stop ]
2
你可以用 splitlines
来把每一行分开,然后再根据 :
来分割每一行,这样就能把它们转换成一个字典,像这样
d = dict(item.split(": ", 1) for item in data.splitlines() if ": " in item)
print d["LOCATION"]
# http://129.94.5.95:80/description.xml
如果你想把字典里的键都变成小写字母,可以这样重建字典
d = dict(item.split(": ", 1) for item in data.splitlines() if ": " in item)
d = {key.lower():d[key] for key in d}
print d["location"]
4
你可以使用正则表达式来提取字符串。
>>> import re
>>> string = """HTTP/1.1 200 OK
... CACHE-CONTROL: max-age=100
... EXT:
... LOCATION: http://129.94.5.95:80/description.xml
... SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1
... ST: urn:schemas-upnp-org:device:basic:1
... USN: uuid:2f402f80-da50-11e1-9b23-0017881892ca
... """
>>> regex = re.compile('LOCATION: (.*?)\n')
>>> m = regex.search(string)
>>> if m:
... print m.group(1)
http://129.94.5.95:80/description.xml
2
你可以把整个字符串按照换行符分开。然后检查每一行是否以LOCATION
开头。如果是的话,就打印出这一行的其余部分。
string = """HTTP/1.1 200 OK
CACHE-CONTROL: max-age=100
EXT:
LOCATION: http://129.94.5.95:80/description.xml
SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1
ST: urn:schemas-upnp-org:device:basic:1
USN: uuid:2f402f80-da50-11e1-9b23-0017881892ca"""
for line in string.split('\n'):
if line.startswith('LOCATION'):
print(line[10:])
break
Out: http://129.94.5.95:80/description.xml