簡體   English   中英

從字符串獲取特定信息

[英]Getting specific information from a string

我有這個人一樣的問題:

在python中分割字符串並獲取冒號后的最后一段的值

我的就像:

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:' ,則以下正則表達式將為您工作:

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

輸出

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

輸出

['Fritzbox', 'Macin', 'IBM']

使用pygrok python包,我們可以以結構化格式從字符串中提取數據。

一個用於解析字符串並從結構化/非結構化數據中提取信息的Python庫。

https://pypi.org/project/pygrok/

點安裝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"]
]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM