获取字符串中的特定单词

时间:2014-02-13 22:45:20

标签: python string string-matching

我对python很新。我有一个这个字符串

"DEALER: 'S up, Bubbless?
BUBBLES: Hey.
DEALER: Well, there you go.
JUNKIE: Well, what you got?
DEALER: I got some starters. "

我试图以冒号结尾的所有单词结尾。例如,我从上面的字符串中获取DEALER,BUBBLES和JUNKIE。谢谢

这是我试过的。似乎工作。但不如我想要的那么准确。

s = "DEALER: 'S up, Bubbless? BUBBLES: Hey. DEALER: Well, there you go. JUNKIE: Well, what you got?DEALER: I got some starters.";
#print l
print [ t for t in s.split() if t.endswith(':') ]

2 个答案:

答案 0 :(得分:2)

你需要摆脱重复。一个很好的方法是使用一套。

import re

mystring = """
DEALER: 'S up, Bubbless?
BUBBLES: Hey.
DEALER: Well, there you go.
JUNKIE: Well, what you got?
DEALER: I got some starters. """

p = re.compile('([A-Z]*):')
s = set(p.findall(mystring))

print s

这会产生一组独特的名称

set(['JUNKIE', 'DEALER', 'BUBBLES'])

答案 1 :(得分:1)

import re 

regex = re.compile( "(?P<name>[A-Z]*:)[\s\w]*" ) 

actors = regex.findall(text)