Как извлечь определенные части строк в Python? - PullRequest
0 голосов
/ 08 марта 2012

Скажите, у меня есть три строки:

abc534loif

tvd645kgjf

tv96fjbd_gfgf

и три списка:

  • beginning захватывает только первую часть строки «имя»
  • middle захватывает только число
  • end содержит только остальные символы после числовой части

Как мне сделать это наиболее эффективным способом?

Ответы [ 7 ]

2 голосов
/ 08 марта 2012

Использовать регулярные выражения?

>>> import re
>>> strings = 'abc534loif tvd645kgjf tv96fjbd_gfgf'.split()
>>> for s in strings:
...   for match in re.finditer(r'\b([a-z]+)(\d+)(.+?)\b', s):
...     print match.groups()
... 
('abc', '534', 'loif')
('tvd', '645', 'kgjf')
('tv', '96', 'fjbd_gfgf')
1 голос
/ 08 марта 2012
>>> import itertools as it
>>> s="abc534loif"
>>> [''.join(j) for i,j in it.groupby(s, key=str.isdigit)]
['abc', '534', 'loif']
1 голос
/ 08 марта 2012

Я думаю, вы ищете re.findall :

strs = """
    abc534loif
    tvd645kgjf
    tv96fjbd_gfgf
"""

import re
print re.findall(r'\b(\w+?)(\d+)(\w+)', strs)

>> [('abc', '534', 'loif'), ('tvd', '645', 'kgjf'), ('tv', '96', 'fjbd_gfgf')]
1 голос
/ 08 марта 2012

Это независимый от языка подход, направленный на повышение эффективности:

  1. найти первую цифру в строке и сохранить ее положение p0
  2. найти последнюю цифру в строке и сохранитьего позиция p1
  3. извлечь подстроку от 0 до p0-1 в beginning
  4. извлечь подстроку от p0 до p1 в middle
  5. извлечь подстроку от p1+1 до length-1 в end
0 голосов
/ 08 марта 2012

Я бы что-то вроде этого:

>>> import re
>>> l = ['abc534loif', 'tvd645kgjf', 'tv96fjbd_gfgf']
>>> regex = re.compile('([a-z_]+)(\d+)([a-z_]+)')
>>> beginning, middle, end = zip(*[regex.match(s).groups() for s in l])
>>> beginning
('abc', 'tvd', 'tv')
>>> middle
('534', '645', '96')
>>> end
('loif', 'kgjf', 'fjbd_gfgf')
0 голосов
/ 08 марта 2012
import re #You want to match a string against a pattern so you import the regular expressions module 're'
mystring = "abc1234def" #Just a string to test with
match = re.match(r"^(\D+)([0)9]+](\D+)$") #Our regular expression. Everything between brackets is 'captured', meaning that it is accessible as one of the 'groups' in the returned match object. The ^ sign matches at the beginning of a string, while the $ matches the end. the characters in between the square brackets [0-9] are character ranges, so [0-9] matches any digit character, \D is any non-digit character.
if match: # match will be None if the string didn't match the pattern, so we need to check for that, as None.group doesn't exist.
    beginning = match.group(1)
    middle = match.group(2)
    end = match.group(3)
0 голосов
/ 08 марта 2012

Я буду использовать регулярные выражения, такие как:

(?P<beginning>[^0-9]*)(?P<middle>[^0-9]*)(?P<end>[^0-9]*)

и вытащить три соответствующих раздела.

import re 

m = re.match(r"(?P<beginning>[^0-9]*)(?P<middle>[^0-9]*)(?P<end>[^0-9]*)", "abc534loif")
m.group('beginning')
m.group('middle')
m.group('end')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...