0

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

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(form-I-need)。
  2. (anytext)(word-I-need)\t \t(form-I-need)。

这是我尝试过的正则表达式:

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

你有什么建议?谢谢!

4

3 回答 3

3
pattern = re.compile(r"\{(?:.*?,|.*?)(\S+)\t \t(.*?)\}")
于 2012-06-09T17:45:25.133 回答
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')
于 2012-06-09T17:44:44.620 回答
0

像这样的东西可能会起作用

([^{\s,]*)\t \t([^}]*)
于 2012-06-09T18:27:40.217 回答