python在tex中的随机语法

2024-10-01 11:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个输入文本文件bio.txt

Enter for a chance to {win|earn|gain|obtain|succeed|acquire|get} 
1⃣Click {Link|Url|Link up|Site|Web link} Below️
2⃣Enter Name
3⃣Do the submit(inside optin {put|have|positioned|set|placed|apply|insert|locate|situate|put|save|stick|know|keep} {shipping|delivery|shipment} adress)

需要像这样定位语法{win | earn | gain | acquire | success | acquire | get}并返回随机词,例如:win

如何在python中找到它从我的代码开始:

input = open('bio.txt', 'r').read()

Tags: totxtforgetputlinkwinbio
2条回答

您可以在每一行用regex搜索您的模式("\{.*\}",根据您的示例)。 找到匹配项后,只需使用分隔符("|"根据您的示例)分割匹配项。 最后随机返回列表中的一个元素

正则表达式文档:https://docs.python.org/2/library/re.html

Python的字符串公共操作doc(包括splithttps://docs.python.org/2/library/string.html

获取列表的随机元素:How to randomly select an item from a list?

首先,需要将文本文件读入字符串;使用regex找到模式“{([a-z |]+)}”,用“|”将它们分割成一个随机词列表。可通过以下方式实现:

import re, random
seed = []
matches = re.findall('{([a-z|]+)}', open('bio.txt', 'r').read())
[seed.extend(i.split('|')) for i in matches]
input = random.choice(seed)

相关问题 更多 >