开发者

How should I extract % delimited tags

开发者 https://www.devze.com 2022-12-27 14:04 出处:网络
I want to get the %tagn开发者_运维百科ame% from a file and copy them to a dictionary only tagname in python.this will get you a list of tags

I want to get the %tagn开发者_运维百科ame% from a file and copy them to a dictionary only tagname in python.


this will get you a list of tags

re.findall("%([^%]+)%", text)


To get the list of tags, you can use the non-greedy version of the + operator, which has the advantage of being simple:

re.findall('%(.+?)%', text)

In fact, .+?% finds all characters of any type (a tag), and stops as soon as % is found (that's the "non-greedy" part).

In the speed test below, the non-greedy version of this answer is slower than the "not another % sign" version by a factor of almost 2, though:

python -m timeit -s'import re; t="%t1% lkj lkj %long tag% lkj lkj"*1000' 're.findall("%([^%]+)%", t)'
1000 loops, best of 3: 874 usec per loop

python -m timeit -s'import re; t="%t1% lkj lkj %long tag% lkj lkj"*1000' 're.findall("%(.+?)%", t)'
1000 loops, best of 3: 1.43 msec per loop
0

精彩评论

暂无评论...
验证码 换一张
取 消