【发布时间】:2014-05-18 08:11:04
【问题描述】:
我编写了一个非常好的程序,它使用文本文件作为词库,用于从句子骨架生成句子。一个例子:
骷髅
“名词擅长动词动词”
可以通过搜索名词和动词的词库来代替骨架中的“名词”和“动词”来造句。我想得到类似的结果
“狗很会捡棍子”
不幸的是,方便的 replace() 方法是为提高速度而设计的,而不是考虑自定义函数。我创建了一些方法来完成从正确的库中选择随机单词的任务,但是做类似骨架 = 骨架.replace('noun', getNoun(file.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()
【问题讨论】:
-
“不幸的是,方便的 replace() 方法是为提高速度而设计的,而不是考虑自定义函数。” - 不,行为只是参数传递如何工作的自然结果。无论您如何实现
replace,在调用replace时,getRandomLine调用已经结束。replace不知道它正在查看的字符串来自getRandomLine调用,并且无法重复调用。 -
这很有趣。您有解决问题的建议吗?
标签: python regex string replace substring