我有一些短信。你可以在这里看到。
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')]正如您在这里看到的,可以有两个变体:
(任意文本,)(字-i-需要)\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')]你有什么建议吗?谢谢!
发布于 2012-06-09 17:45:25
pattern = re.compile(r"\{(?:.*?,|.*?)(\S+)\t \t(.*?)\}")发布于 2012-06-09 17:44:44
这将是少数人的观点,但是为什么不使用regex逻辑来处理更容易用regex编写的东西,然后再用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-09 18:27:40
像这样的事情可能会奏效
([^{\s,]*)\t \t([^}]*)https://stackoverflow.com/questions/10962983
复制相似问题