获取字符串中的特定单词

2024-09-28 03:16:53 发布

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

我对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(':') ]

Tags: yougosomewhatthereprintupwell
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'])
import re 

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

actors = regex.findall(text)

相关问题 更多 >

    热门问题