1

我有以下['You and i','everyone else','cat and dog','We u all']

and我需要以某种方式识别and旁边的字符串u

例如,我期望以下输出:

一世

我们

全部

and基本上,每个句子都应该从和中分离出来u。我需要打印and和两侧的两个文本。u

我所做的是错误的,但这是我的尝试之一:

sen = [w for w in words if re.search(r'.*and*.','.*u*.', w)]
for st in sen:
    print st
4

3 回答 3

2

遍历每一行。检测是否有andu。如果是,则在该令牌上拆分它并最后打印。对于所有其他行忽略。

>>> sentences = ['You and i', 'everyone else', 'cat and dog', 'We u all']
>>> for line in sentences:
...     if 'and' in line:
...         for split_word in line.split('and'):
...             print split_word.strip()
...     elif ' u ' in line:
...         for split_word in line.split(' u '):
...             print split_word.strip()
...     else:
...         pass
... 
You
i
cat
dog
We
all
>>> 
于 2013-08-01T10:07:51.850 回答
1

你可以做:

>>> import re
>>> words = ['You and i', 'everyone else', 'cat and dog', 'We u all']
>>> res = [re.search(r'(.*?) (and|u) (.*?)$', word) for word in words]
>>> for i in res:
...     if i is not None:
...             print i.group(1)
...             print i.group(3)
... 
You
i
cat
dog
We
all
于 2013-08-01T10:10:09.120 回答
1
l = ['You and i','everyone else','cat and dog','We u all']

# Iterate.
for i in l:
    words = None

    # Split.
    if ' and ' in i:
        words = i.split(' and ')
    elif ' u ' in i:
        words = i.split(' u ')

    # Print.
    if words:
        for word in words:
            print word

结果:

You
i
cat
dog
We
all
于 2013-08-01T10:11:50.713 回答