基本上我有一个python脚本加载到许多文件中,每个文件都包含一个列表,这些文件用于生成字符串。例如:"只是在$ location%中看到$ film%,我强烈推荐它!"我需要用它们各自导入列表的数组的随机元素替换$ film%和$ location%占位符。
我对Python很陌生,但很容易掌握它,但很明显Python字符串是不可变的,因此与我使用的其他语言相比,处理这类任务是不同的。
以下是代码,我尝试在while循环中添加,但它仍然只会替换可替换单词的第一个实例而留下其余部分。
#!/usr/bin/python
import random
def replaceWord(string):
#Find Variable Type
if "url" in string:
varType = "url"
elif "film" in string:
varType = "film"
elif "food" in string:
varType = "food"
elif "location" in string:
varType = "location"
elif "tvshow" in string:
varType = "tvshow"
#LoadVariableFile
fileToOpen = "/prototype/default_" + varType + "s.txt"
var_file = open(fileToOpen, "r")
var_array = var_file.read().split('\n')
#Get number of possible variables
numberOfVariables = len(var_array)
#ChooseRandomElement
randomElement = random.randrange(0,numberOfVariables)
#ReplaceWord
oldValue = "$" + varType + "%"
newString = string.replace(oldValue, var_array[randomElement], 1)
return newString
testString = "Just been to see $film% in $location%, I'd highly recommend it!"
Test = replaceWord(testString)
这会产生以下结果:只是在$ location%看到哈利波特,我强烈推荐它!
我尝试过使用while循环,计算字符串中要替换的单词数等,但它仍然只会更改第一个单词。它还需要能够替换相同的"变量"的多个实例。键入相同的字符串,因此如果字符串中出现两次$ film%,则应使用加载文件中的随机元素替换它们。
答案 0 :(得分:1)
以下程序可能会更接近您要完成的任务。请注意,已包含文档以帮助解释发生的情况。模板与您的模板略有不同,但提供了自定义选项。
#! /usr/bin/env python3
import random
PATH_TEMPLATE = './prototype/default_{}s.txt'
def main():
"""Demonstrate the StringReplacer class with a test sting."""
replacer = StringReplacer(PATH_TEMPLATE)
text = "Just been to see {film} in {location}, I'd highly recommend it!"
result = replacer.process(text)
print(result)
class StringReplacer:
"""StringReplacer(path_template) -> StringReplacer instance"""
def __init__(self, path_template):
"""Initialize the instance attribute of the class."""
self.path_template = path_template
self.cache = {}
def process(self, text):
"""Automatically discover text keys and replace them at random."""
keys = self.load_keys(text)
result = self.replace_keys(text, keys)
return result
def load_keys(self, text):
"""Discover what replacements can be made in a string."""
keys = {}
while True:
try:
text.format(**keys)
except KeyError as error:
key = error.args[0]
self.load_to_cache(key)
keys[key] = ''
else:
return keys
def load_to_cache(self, key):
"""Warm up the cache as needed in preparation for replacements."""
if key not in self.cache:
with open(self.path_template.format(key)) as file:
unique = set(filter(None, map(str.strip, file)))
self.cache[key] = tuple(unique)
def replace_keys(self, text, keys):
"""Build a dictionary of random replacements and run formatting."""
for key in keys:
keys[key] = random.choice(self.cache[key])
new_string = text.format(**keys)
return new_string
if __name__ == '__main__':
main()
答案 1 :(得分:0)
关于代码的几点:
这样的事情:
#!/usr/bin/python
import random
def replaceWord(string):
#Find Variable Type
types = ("url", "film", "food", "location", "tvshow")
for t in types:
if "$" + t + "%" in string:
var_array = []
#LoadVariableFile
fileToOpen = "/prototype/default_" + varType + "s.txt"
with open(fname) as f:
var_array = f.readlines()
tag = "$" + t + "%"
while tag in string:
choice = random.choice(var_array)
string = string.replace(tag, choice, 1)
var_array.remove(choice)
return string
testString = "Just been to see $film% in $location%, I'd highly recommend it!"
new = replaceWord(testString)
print(new)
答案 2 :(得分:0)
您分配的varType
将仅在您的if-elif-else
序列中设置一个,然后解释器就会转到外面。您必须遍历它并执行操作。一种方法是设置标志,你要改变哪一部分句子。它会这样:
url_to_change = False
film_to_change = False
if "url" in string:
url_to_change = True
elif "film" in string:
film_to_change = True
if url_to_change:
change_url()
if film_to_change:
change_film()
如果您想要更改所有出现,可以使用foreach
循环。在你交换一个单词的部分做这样的事情:
for word in sentence:
if word == 'url':
change_word()
话虽如此,我建议引入两项改进措施。推送到单独的功能。管理代码会更容易。 例如,用于从文件到随机获取项目的功能可以是
def load_variable_file(file_name)
fileToOpen = "/prototype/default_" + file_name + "s.txt"
var_file = open(fileToOpen, "r")
var_array = var_file.read().split('\n')
var_file.clos()
return var_array
而不是
if "url" in string:
varType = "url"
你可以这样做:
def change_url(sentence):
var_array = load_variable_file(url)
numberOfVariables = len(var_array)
randomElement = random.randrange(0,numberOfVariables)
oldValue = "$" + varType + "%"
return sentence.replace(oldValue, var_array[randomElement], 1)
if "url" in sentence:
setnence = change_url(sentence)
等等。您可以将我放入change_url()的部分内容推送到一个单独的函数中,因为它将被所有这些函数使用(就像从文件加载数据一样)。我故意不改变一切,我希望你明白我的意思。正如您所看到的具有清晰名称的函数,您可以编写更少的代码,将其拆分为逻辑的,可重用的部分,无需对代码进行注释。