Python返回下一个单词/数字

时间:2016-02-25 02:28:22

标签: python

bool mod_enabled = true;        //Enable/Disable
BYTE display_delay = 15;        //Redisplay delay

打印返回

s= '''number 100-200-300
    number 200-400-500
    number 200-500-300
    numb   undefined
    gone  300-400-500
    going 400-500-300

    stop
    This is some kind of number but doesn't print
    number 300-400-500
    number 200-100-400
'''
sl = s.split()

def nextword(target, source):
    for i, w in enumerate(source):
        if w == target:
            return (source[i+1])

但是,我想返回所有数字,而不是只返回第一个数字。

打印下一个字('数字' /'' /' go',sl)?

print nextword('number', sl)    
'100-200-300'

4 个答案:

答案 0 :(得分:1)

如果你需要你的功能,那么你需要的是一个发电机:

def nextword(target, source):
    for i, w in enumerate(source):
        if w == target:
            yield source[i+1]

但是python也有生成器表达式,这与上面的相同:

print '\n'.join(s1[i+1] for i, w in enumerate(s1) if w == 'number')

但你也可以这样做:

s1 = iter(s.split())
print '\n'.join(x for w, x in zip(s1, s1) if w == 'number')

**更新:基于OP编辑。在'\n'上拆分然后拆分行更容易:

def nextword(target, source):
    for s in source:
        s1 = s.split()
        if not s1:   # Blank lines
            continue
        if any(s1[0].startswith(t) for t in target):
            yield s1[1]
        if s1[0] == 'stop':
            yield 'stop'

print('\n'.join(nextword(['numb', 'go'], s.split('\n'))))

输出:

100-200-300
200-400-500
200-500-300
undefined
300-400-500
400-500-300
stop
300-400-500
200-100-400

答案 1 :(得分:0)

您可以结合使用str.splitlines()str.split()

print([line.split()[-1] for line in s.splitlines()])

打印['100-200-300', '200-400-500', '200-500-300', 'undefined']

请注意,您可以在每一行上另外应用检查,例如:

[line.split()[-1] for line in s.splitlines() if "numb" in line]

答案 2 :(得分:0)

您可以使用re.findall()

import re
print re.findall('\d{3}-\d{3}-\d{3}|undefined', s)

答案 3 :(得分:0)

返回一个数字列表,然后按照您的意愿执行:

def nextword(target, source):
    words = []
    for i, w in enumerate(source):
        if w == target:
            words.append(source[i+1])
    return words

然后,既然您有一个列表,则每行打印一个单词:

print '\n'.join(nextword('number', sl))

要进行部分匹配,您可以使用in

def nextword(target, source):
    words = []
    for i, w in enumerate(source):
        if target in w:
            words.append(source[i+1])
    return words

根据AChampion的建议,最好使用yield

def nextword(target, source):
    for i, w in enumerate(source):
        if target in w:
            yield source[i+1]

要打印stop,无论target是什么:

def nextword(target, source):
    for i, w in enumerate(source):
        if w == 'stop':
            yield w
        elif target in w:
            yield source[i+1]

要匹配多个字词,请使用target的列表与any匹配,以匹配其中任何字词:

def nextword(target, source):
    words = []
    for i, w in enumerate(source):
        if any(t in w for t in target):
            yield source[i+1]

print ('\n'.join(nextword(['num', 'go'], sl)))