-2

如何替换 pyPEG 中的某些单词?例如我有句子

约翰踢足球

我想将John替换为Bob并将其组合为:

鲍勃踢足球

from pypeg2 import *

class Try(str):

    grammar = 'John ', restline

    # I am think that here should be same callback function, but i have no idea how to type it

f = parse("John plays football", Try)

print(compose(f))

输出:

John plays football
4

1 回答 1

0

“John”是第一个被替换的参数,“Bob”是替换字符串。

使用.replace(something, with_something_else).

from pypeg2 import *

def Try(String):

    grammar = 'John'
    String = String.replace(grammar, 'Bob')
    return String

f = Try("John plays football")

print(f)

输出:

"Bob plays football"
于 2017-08-19T10:58:25.127 回答