Имя Python граббер - PullRequest
       6

Имя Python граббер

0 голосов
/ 02 ноября 2009

если у меня есть строка в формате

(статическая строка) имя (другая статическая строка) сообщение (последняя статическая строка)

(статическая строка) имя (другая статическая строка) сообщение (последняя статическая строка)

(статическая строка) имя (другая статическая строка) сообщение (последняя статическая строка)

(статическая строка) имя (другая статическая строка) сообщение (последняя статическая строка)

Каков наилучший способ поиска в сообщениях по слову и создания массива всех имен, которые имели это слово в сообщении?

Ответы [ 4 ]

3 голосов
/ 02 ноября 2009
>>> s="(static string) name (different static string ) message (last static string)"
>>> _,_,s=s.partition("(static string)")
>>> name,_,s=s.partition("(different static string )")
>>> message,_,s=s.partition("(last static string)")
>>> name
' name '
>>> message
' message '
0 голосов
/ 03 ноября 2009
for line in open("file"):
    line=line.split(")")
    for item in line:
        try:
            print item[:item.index("(")]
        except:pass

выход

$ more file
(static string) name (different static string ) message (last static string)
(static string) name (different static string ) message (last static string)
(static string) name (different static string ) message (last static string)
(static string) name (different static string ) message (last static string)
$ python python.py

 name
 message

 name
 message

 name
 message

 name
 message
0 голосов
/ 03 ноября 2009

Вот полный ответ, показывающий, как это сделать, используя replace().

strings = ['(static string) name (different static string ) message (last static string)',
           '(static string) name (different static string ) message (last static string)',
           '(static string) name (different static string ) message (last static string)',
           '(static string) name (different static string ) message (last static string)',
           '(static string) name (different static string ) message (last static string)',
           '(static string) name (different static string ) message (last static string)']

results = []
target_word = 'message'
separators = ['(static string)', '(different static string )', '(last static string)']

for s in strings:
    for sep in separators:
        s = s.replace(sep, '')
    name, message = s.split()
    if target_word in message:
        results.append((name, message))

>>> results
[('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message'), ('name', 'message')]

Обратите внимание, что это будет соответствовать любой message, которая содержит подстроку target_word. Он не будет искать границы слов, например сравните прогон этого с target_word = 'message' против target_word = 'sag' - даст те же результаты. Вам может понадобиться регулярное выражение, если ваше сопоставление слов более сложное.

0 голосов
/ 02 ноября 2009

Ожидается эта строка:

Foo NameA Bar MessageA Baz

это регулярное выражение будет соответствовать:

Foo\s+(\w+)\s+Bar\s+(\w+)\s+Baz

Группа 1 будет именем, группа 2 будет сообщением. FooBarBaz являются статическими частями.

Здесь используется ответ Python:

Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> s = "Foo NameA Bar MessageA Baz"
>>> m = re.match("Foo\s+(\w+)\s+Bar\s+(\w+)\s+Baz", s)
>>> m.group(0)
'Foo NameA Bar MessageA Baz'
>>> m.group(1)
'NameA'
>>> m.group(2)
'MessageA'
>>> 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...