如何在不同时替换所有子字符串的情况下替换子字符串?Python

2024-09-28 04:48:12 发布

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

我写了一个非常好的程序,使用文本文件作为词库,从句子骨架生成句子。例如:

骨架
“这个名词擅长冗长名词”
可以通过搜索名词和动词的词库来替换骨架中的“名词”和“动词”而组成一个句子。我想得到一个结果,比如
“这条狗很会拿棍子”

不幸的是,handy replace()方法是为速度而设计的,而不是为定制函数而设计的。我做了一些方法来完成从正确的库中选择随机单词的任务,但是做一些类似skeleton=骨架.替换('getNoun'(文件.txt))用getNoun()的单个调用替换“noun”的所有实例,而不是每次替换都调用它。所以句子看起来像

“这条狗很会抓狗”

如何解决replace()的这一特性,并使每次替换都调用我的方法?我的最小长度代码如下。在

import random

def getRandomLine(rsv):
    #parameter must be a return-separated value text file whose first line contains the number of lines in the file.
    f = open(rsv, 'r') #file handle on read mode
    n = int(f.readline()) #number of lines in file
    n = random.randint(1, n) #line number chosen to use
    s = "" #string to hold data
    for x in range (1, n):
        s = f.readline()
    s = s.replace("\n", "")
    return s

def makeSentence(rsv):
    #parameter must be a return-separated value text file whose first line contains the number of lines in the file.
    pattern = getRandomLine(rsv) #get a random pattern from file
    #replace word tags with random words from matching files
    pattern = pattern.replace('noun', getRandomLine('noun.txt'))
    pattern = pattern.replace('verb', getRandomLine('verb.txt'))

    return str(pattern);

def main():
    result = makeSentence('pattern.txt');
    print(result)

main()

Tags: the方法intxtnumberreturnrandomreplace
2条回答

我不知道您是要求编辑代码还是编写新代码,所以我编写了新代码:

import random
verbs = open('verb.txt').read().split()
nouns = open('noun.txt').read().split()

def makeSentence(sent):
    sent = sent.split()
    for k in range(0, len(sent)):
            if sent[k] == 'noun':
                    sent[k] = random.choice(nouns)
            elif sent[k] == 'nouns':
                    sent[k] = random.choice(nouns)+'s'
            elif sent[k] == 'verbing':
                    sent[k] = random.choice(verbs)

    return ' '.join(sent)

var = raw_input('Enter: ')
print makeSentence(var)

其运行方式如下:

^{pr2}$

re模块的^{}函数完成了str.replace所做的工作,但功能要多得多。特别是,它提供了传递替换函数而不是字符串的能力。对于每个匹配调用一次函数,并将匹配对象作为参数,并且必须返回将替换匹配项的字符串:

import re
pattern = re.sub('noun', lambda match: getRandomLine('noun.txt'), pattern)

这里的好处是增加了灵活性。缺点是,如果您不知道regex,那么替换者将'noun'解释为regex这一事实可能会引起意外。例如

^{pr2}$

如果您不知道regex,您可能需要使用re.escape来创建一个与要搜索的原始文本匹配的regex,即使文本包含regex元字符:

>>> re.sub(re.escape('Aw, man...'), 'Match found.', 'Aw, manatee.')
'Aw, manatee.'

相关问题 更多 >

    热门问题