gpt4 book ai didi

python - 在Python中替换来自不同数据集的字符串中的多个单词

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:26 25 4
gpt4 key购买 nike

本质上,我有一个 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% ,则应将两者替换为加载文件中的随机元素。

最佳答案

以下程序可能更接近您想要完成的任务。请注意,其中包含文档以帮助解释正在发生的事情。这些模板与您的模板略有不同,但提供自定义选项。

#! /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()

关于python - 在Python中替换来自不同数据集的字符串中的多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38977756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com