Python名称抓取器

时间:2009-11-02 06:43:20

标签: python regex parsing

如果我有一个格式为

的字符串

(静态字符串)名称(不同的静态字符串)消息(最后一个静态字符串)

(静态字符串)名称(不同的静态字符串)消息(最后一个静态字符串)

(静态字符串)名称(不同的静态字符串)消息(最后一个静态字符串)

(静态字符串)名称(不同的静态字符串)消息(最后一个静态字符串)

在消息中搜索单词的最佳方法是什么,并生成一个包含其消息中包含该单词的所有名称的数组?

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

期待这个字符串:

Foo NameA Bar MessageA Baz

这个正则表达式将匹配:

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

组1将是名称,组2将是消息。 FooBarBaz是静态部分。

这里使用的是Python的repl:

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

答案 2 :(得分:0)

以下是一个完整的答案,展示了如何使用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'进行比较 - 将产生相同的结果。如果你的单词匹配更复杂,你可能需要正则表达式。

答案 3 :(得分:0)

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
相关问题