查找任何带有逗号或sp的文本

2024-09-27 19:14:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些短信。你可以在这里看到。你知道吗

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. (任意文本,)(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')]

你有什么建议?谢谢!你知道吗


Tags: vocneedsgnomdatgenplfem
3条回答

像这样的东西可能有用

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

这将是少数人的观点,但是为什么不使用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')
pattern = re.compile(r"\{(?:.*?,|.*?)(\S+)\t \t(.*?)\}")

相关问题 更多 >

    热门问题