【问题标题】:extracting unknown substring from a string in python [duplicate]从python中的字符串中提取未知子字符串[重复]
【发布时间】:2014-07-26 00:51:41
【问题描述】:

我有以下字符串:

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' ??

【问题讨论】:

标签: python string dictionary


【解决方案1】:

您使用正则表达式提取字符串

>>> 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

【讨论】:

  • 这个正则表达式变量是一个字符串吗?
  • 不是,但是regex.group(1) 是一个字符串。
  • 您可能希望将搜索和组提取分开,以便在没有匹配项的情况下测试None
  • 是的,正如@Adam 所说,regex.group(1) 是字符串。
  • 你的回答拯救了我的一天,谢谢
【解决方案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

【讨论】:

  • 几个原因:代码的解释,在人们可能复制和粘贴的示例中隐藏str内置类型,硬编码值10,缩进不好。就目前而言,@thefourtheye 的解决方案要好得多,并且可以解决一般情况。
【解决方案3】:

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 ]

【讨论】:

  • 阅读我的更新,很抱歉我的第一个答案拼错了。
  • 这是不正确的。它产生字符串“:要提取的字符串,后跟一个”。
  • Adam :嗯,这正是字符串中的内容,请阅读问题!
【解决方案4】:

您可以使用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"]

【讨论】:

  • 反对者,请告诉我如何改进这篇文章。
  • 哎呀,我非常喜欢你的解决方案,我删除了我基于 RE 的解决方案。
  • 是否可以在不影响值的情况下将此字典的键小写?
  • @sukhvir 只有钥匙?
  • @sukhvir 现在请检查我的答案。
猜你喜欢
  • 2012-02-28
  • 1970-01-01
  • 2017-12-30
  • 2020-05-14
  • 2020-11-26
  • 1970-01-01
  • 2023-01-07
  • 2016-06-01
  • 2021-01-13
相关资源
最近更新 更多