我写了一个非常好的程序,使用文本文件作为词库,从句子骨架生成句子。例如:
骨架
“这个名词擅长冗长名词”
可以通过搜索名词和动词的词库来替换骨架中的“名词”和“动词”而组成一个句子。我想得到一个结果,比如
“这条狗很会拿棍子”
不幸的是,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()
我不知道您是要求编辑代码还是编写新代码,所以我编写了新代码:
其运行方式如下:
^{pr2}$re
模块的^{str.replace
所做的工作,但功能要多得多。特别是,它提供了传递替换函数而不是字符串的能力。对于每个匹配调用一次函数,并将匹配对象作为参数,并且必须返回将替换匹配项的字符串:这里的好处是增加了灵活性。缺点是,如果您不知道regex,那么替换者将
^{pr2}$'noun'
解释为regex这一事实可能会引起意外。例如如果您不知道regex,您可能需要使用
re.escape
来创建一个与要搜索的原始文本匹配的regex,即使文本包含regex元字符:相关问题 更多 >
编程相关推荐