python - 这个python字符串怎么分解
问题描述
我需要按照以下示例中所示的格式将 python 字符串分解为字符串列表。
例子
有一个 python 字符串看起来像:
[1] 输入:
'they <are,are not> sleeping'
它必须变成一个列表,看起来像:
[1] 输出:
['they are sleeping', 'they are not sleeping']
另一个例子
[2] 输入:
'hello <stupid,smart> <people,persons,animals>'
[2] 输出:
['hello stupid people', 'hello stupid persons', 'hello stupid animals', 'hello smart people', 'hello smart persons', 'hello smart animals']
替代选项存在于标签中,并且需要考虑所有可能性来生成新字符串。
解决方案
试试这个:
import itertools
def all_choices(text):
"""
>>> list(all_choices('they <are,are not> sleeping'))
['they are sleeping', 'they are not sleeping']
>>> list(all_choices('hello <stupid,smart> <people,persons,animals>'))
['hello stupid people', 'hello stupid persons', 'hello stupid animals', 'hello smart people', 'hello smart persons', 'hello smart animals']
"""
tokens = (block2 for block1 in text.split('<')
for block2 in block1.split('>'))
decisions = []
literals = []
try:
while True:
literal = next(tokens)
literals.append(literal)
options = next(tokens).split(',')
decisions.append(options)
except StopIteration:
pass
decisions.append(('',))
for choices in itertools.product(*decisions):
yield ''.join(x for pair in zip(literals, choices)
for x in pair)
推荐阅读
- python - linux中的pythonnet无法导入ssl
- javascript - 如何将副本与括号 Javascript 匹配
- adb - 启用安全 ADB 模式
- python-3.x - python3在文件结束后重置标准输入
- flutter - 在android上重新启动应用程序后显示Flutter hive数据
- xamarin.forms - telerikInput:RadAutoCompleteView 关闭图标颜色变化
- javascript - 管理网站的文件和扩展名
- javascript - 如何使用正则表达式将 HTML 标签包裹在占位符周围?
- python - 如何为多索引熊猫数据框组合重复的标题列?
- jquery - 格式化数据表中的日期列