[英]Python Get Random Choice From Text File Then Repeat That Choice
This may seem rudimentary but I'm drawing a blank on how to accomplish this. 这看似基本,但我在如何实现这一目标上处于空白。 It's basically for a href link and anchor text.
它基本上是用于href链接和锚文本的。 I need to go get a random line from a text file, create the html code and then repeat the random choice I gathered as the anchor text.
我需要从文本文件中获取随机行,创建html代码,然后重复我作为锚文本收集的随机选择。 Here is my code thus far.
到目前为止,这是我的代码。 How would I repeat my choice I got from the text file for my anchor text?
如何重复从文本文件中选择的锚文本? Thank you for the help.
感谢您的帮助。
'<p><a href="/' + random.choice(list(open('data_files/script_only_files/titles.csv'))).replace(" ", "-").replace("---", "-").replace("\n", "").lower() + '/">' + random.choice(list(open('data_files/script_only_files/titles.csv'))).replace("\n", "") + '</a></p>'
This code works fine to get the url for the href but as you can see it also gets a random anchor text, which is not what I'm wanting to achieve. 这段代码可以很好地获取href的网址,但是如您所见,它还可以获取随机锚文本,这不是我想要的。 An example output I need to achieve would be like this:
我需要实现的示例输出如下所示:
<a href="/my-funny-wordpress-page/">My Funny Wordpress Page</a>
Thank you. 谢谢。
Can you use a variable ? 可以使用变量吗?
mychoice = random.choice(list(open('data_files/script_only_files/titles.csv')))
mytag = '<p><a href="/' + mychoice.replace(" ", "-").replace("---", "-").replace("\n", "").lower() + '/">' + mychoice.replace("\n", "") + '</a></p>'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.