识别文本之间的字符串值

时间:2013-08-01 10:02:10

标签: python

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

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

例如,我希望得到以下输出:

  

     

     

     

     

我们

     

所有

基本上,每个句子应该从andu分开。我需要打印andu两侧的两个文字。

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

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

3 个答案:

答案 0 :(得分: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
>>> 

答案 1 :(得分: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

答案 2 :(得分: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