有没有办法一次进行多个不同的字符串更换?
由于我们被排除在使用任何网络报废库之外
def print_ticket():
if event.get() == 1:
web_page = urlopen(url1)
html_code = web_page.read().decode("UTF-8")
web_page.close()
event_title = findall('<h6.*>(.+)</h6>', html_code)[0]
event_image = findall('<img.* src="([^"]+)".*>', html_code)[4]
event_url = 'https://suncorpstadium.com.au/what-s-on.aspx'
event_details = findall('<h7.*>(.+)</h7>', html_code)[1]
filename = event_title.replace(' ', '_') + '_Ticket.html'
html_file = open(filename, 'w')
html_file.write(ticket_template.replace('EVENT TITLE', event_title + ' Ticket'))
html_file.write(ticket_template.replace('IMAGE', event_image))
html_file.write(ticket_template.replace('DATE TIME', event_details))
我正在做大学作业, 该事件在我的GUI中,我的Web文档打印了3个不同的模板集,每个部分都在一个部分上替换。
有没有一种方法可以立即制作多个 .replaces
而没有打印我的模板的多个副本?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于您正在调用
Write
3次,您只需要调用一次即可。因此,您可以做什么:这样它将起作用,您只会拥有
ticket_template
的最终输出。另外,您可以将其减少到单线,但看起来不会清晰The problem is that you are calling
write
3 times and you need to call it just once. So what you could do:in that way it will work, and you will only have the final output of the
ticket_template
. Also you can reduce this to a one-liner but it won't look legible您可以使用“ f-string”或文字 。为了控制其评估,必须指定它为从a “ nofollow noreferrer”>
) lambda
函数如下所示。
请注意,使用的变量名称不必为
all_caps
,如图所示 - 我只是这样做的,使其更容易发现使用它们的位置。You can do it using an "f-string" or Formatted string literal which was introduced in Python 3.6. To control its evaluation, it must be specified as the result returned from a
lambda
function as shown in the sample code below.Note that the variable names used do not have to be
ALL_CAPS
as shown — I only did it that way to make it easier to spot where they're being used.