我和这个家伙有同样的问题:
partition string in python and get value of last segment after colon
我的就像:
IP-Adress: 1.1.1.1 Device: Fritzbox Serialnumber: 123456789
我想只获取设备,所以我的输出应该是这样的:“Fritzbox”我不需要任何其他东西。
result = mystring.rpartition(':')[2]
这种代码有可能吗?如果是的话,我必须改变什么才能减少休息?
你可以在这里使用re.split
并使用结果创建一个字典 - 这样你就可以访问你想要的任何键,例如:
import re
text = 'IP-Adress: 1.1.1.1 Device: Fritzbox Serialnumber: 123456789 Description: something or other here test: 5'
split = re.split(r'\s*(\S+):\s+', text)
data = dict(zip(split[1::2], split[2::2]))
这给你一个data
:
{'IP-Adress': '1.1.1.1',
'Device': 'Fritzbox',
'Serialnumber': '123456789',
'Description': 'something or other here',
'test': '5'}
然后根据需要访问,例如:
device = data.get('Device', '***No Device Found???***')
通过这种方式,您可以访问所有键/值对,但它不依赖于键的任何排序,也不依赖于它们在文本中的实际存在。
假设'Device:'
始终存在,以下Regular expression应该适合您:
s = 'IP-Adress: 1.1.1.1 Device: Fritzbox Serialnumber: 123456789'
import re
re.search(r'Device:\s*(\w+)', s).group(1)
# 'Fritzbox'
或者,如果您更喜欢字符串方法,您可以执行以下操作:
s.split(':')[-2].strip().split()[0]
# 'Fritzbox'
假设Device:
和Serialnumber
总是存在:
s = 'IP-Adress: 1.1.1.1 Device: Fritzbox Serialnumber: 123456789'
def GetInBetween(s, st, ed):
return (s.split(st))[1].split(ed)[0]
print(GetInBetween(s, 'Device:', 'Serialnumber').strip())
OUTPUT:
Fritzbox
编辑:
如果您有这些字符串的列表:
sList = ['IP-Adress: 1.2.2.2 Device: Fritzbox Serialnumber: 123456789',
'IP-Adress: 1.3.4.3 Device: Macin Serialnumber: 123456789',
'IP-Adress: 1.123.12.11 Device: IBM Serialnumber: 123456789',
]
for elem in sList:
print(GetInbetween(elem, 'Device:', 'Serialnumber').strip())
要么
使用list comprehension
:
print([GetInbetween(x, 'Device:', 'Serialnumber').strip() for x in sList])
OUTPUT:
['Fritzbox', 'Macin', 'IBM']
使用pygrok python包,我们可以以结构化格式从字符串中提取数据。
一个Python库,用于解析字符串并从结构化/非结构化数据中提取信息。
https://pypi.org/project/pygrok/
pip安装pygrok
from pygrok import Grok
text = 'IP-Adress: 1.1.1.1 Device: Fritzbox Serialnumber: 123456789'
pattern = 'IP-Adress: 1.1.1.1 Device: %{WORD:device} Serialnumber: 123456789'
grok = Grok(pattern)
print (grok)
#output
{
"device": [
["Fritzbox"]
]
}