替换pyPEG中的函数

2024-06-14 16:50:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

约翰踢足球

我想把约翰替换成鲍勃,然后写成:

鲍勃踢足球。你知道吗

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

Tags: fromimportjohn单词class句子trystr
1条回答
网友
1楼 · 发布于 2024-06-14 16:50:34

“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"

相关问题 更多 >