查找包含逗号或空格的任何文本

时间:2012-06-09 17:18:22

标签: python regex

我有一些文字。你可以在这里看到它。

str1 = '{5723647 9 aqua\t \tfem nom/voc pl}{5723647 9 aqua\t \tfem dat sg}{5723647 9 aqua\t \tfem gen sg}'
str2 = '{27224035 2 equo_,equus#1\t \tmasc abl sg}{27224035 2 equo_,equus#1\t \tmasc dat sg}'

这是我想要的:

result1 = [('aqua', 'fem nom/voc pl'), ('aqua', 'fem dat sg'), ('aqua', 'fem gen sg')]
result2 = [('equus#1', 'masc abl sg'), ('equus#1', 'masc dat sg')]

如您所见,这可以是两种变体:

  1. (anytext,)(word-I-need)\ t \ t(形式我需要)。
  2. (anytext)(word-I-need)\ t \ t(表格我需要)。
  3. 这是我试过的正则表达式:

    pattern = re.compile(r'\d* \d*(?:,| )(.*?)\t \t(.*?)}')
    

    这是我得到的:

    [('aqua', 'fem nom/voc pl'), ('aqua', 'fem dat sg'), ('aqua', 'fem gen sg')]
    [('equo_,equus#1', 'masc abl sg'), ('equo_,equus#1', 'masc dat sg')]
    

    然而,第二个必须是:

    [('equus#1', 'masc abl sg'), ('equus#1', 'masc dat sg')]
    

    你有什么建议吗?谢谢!

3 个答案:

答案 0 :(得分:3)

pattern = re.compile(r"\{(?:.*?,|.*?)(\S+)\t \t(.*?)\}")

答案 1 :(得分:1)

这将是一个少数意见,但为什么不使用正则表达式逻辑来使用正则表达式更容易编写的东西,然后使用Python呢?除此之外,它对变化更加强大。像

这样的东西
>>> import re
>>> 
>>> str1 = '{5723647 9 aqua\t \tfem nom/voc pl}{5723647 9 aqua\t \tfem dat sg}{5723647 9 aqua\t \tfem gen sg}'
>>> str2 = '{27224035 2 equo_,equus#1\t \tmasc abl sg}{27224035 2 equo_,equus#1\t \tmasc dat sg}'
>>> 
>>> pattern = re.compile("{([^\}]*)}")
>>> 
>>> def extract(part):
...     ps = part.split()
...     word = ps[2].split(',')[-1]
...     form = ' '.join(ps[3:])
...     return word, form
... 
>>> for s in str1, str2:
...     for entry in re.findall(pattern, s):
...         print extract(entry)
... 
('aqua', 'fem nom/voc pl')
('aqua', 'fem dat sg')
('aqua', 'fem gen sg')
('equus#1', 'masc abl sg')
('equus#1', 'masc dat sg')

答案 2 :(得分:0)

这样的事情可能会起作用

([^{\s,]*)\t \t([^}]*)