通过其标记的Python

加入整个单词

让说,我有这样的句子:通过其标记的Python

His/O name/O is/O Petter/Name Jack/Name and/O his/O brother/O name/O is/O 

Jonas/Name Van/Name Dame/Name

我怎样才能得到这样的:

Petter Jack, Jonas Van Dame. 

到目前为止,我已经尝试过这一点,但仍它只是加入2个字:

import re 

pattern = re.compile(r"\w+\/Name)

sent = sentence.split()

for i , w in sent:

if pattern.match(sent[i]) != None:

if pattern.match(sent[i+1]) != None:

#....

#join sent[i] and sent[i+1] element

#....

回答:

尝试是这样的

pattern = re.compile(r"((\w+\/Name\s*)+)") 

names = pattern.findall(your_string)

for name in names:

print(''.join(name[0].split('/Name')))

回答:

我在考虑一个两相溶液

r = re.compile(r'\w+\/Name(?:\ \w+\/Name)*')  

result = r.findall(s)

# -> ['Petter/Name Jack/Name', 'Jonas/Name Van/Name Dame/Name']

for r in result:

print(r.replace('/Name', ''))

# -> Petter Jack

# -> Jonas Van Dame

以上是 通过其标记的Python 的全部内容, 来源链接: utcz.com/qa/261078.html

回到顶部