請注意,我沒有與解析,並用正則表達式的經驗非常有限的經驗。這對我來說不僅僅是一種解決方案,更是一項挑戰,但不管它對您有用。
你的語法並不那麼遙遠從蟒蛇發生器,有效的Python發生器,可產生你想要看起來像這樣的價值觀:
def temp():
for _ in range(2):
yield 'a'
for _ in range(3):
yield 'b'
yield 'c'
所以只有兩個換人,你將不得不作出中,for n
爲for _ in range(n)
:
def sub_for(match):
return "_ in range({})".format(match.group(0))
def my_code_to_generator(code):
# match a number that is preceded by "for " and right before a ":"
code = re.sub("(?<=for)\d+(?=:)",sub_for,code)
...
和不斷變化的任意字母a
到yield語句yield 'a'
:
def sub_letter(match):
return "yield {!r}".format(match.group(0))
def my_code_to_generator(code):
code = re.sub("(?<=for)\d+(?=:)",sub_for,code)
#match a single character that has whitespace around it.
code = re.sub("(?<=\s)[A-Za-z](?=\s)", sub_letter, code)
....
然後把它在一個def
語句並執行它作爲Python代碼會產生生成你想要的字符的迭代器:
import re
def sub_for(match):
return "_ in range({})".format(match.group(0))
def sub_letter(match):
return "yield {!r}".format(match.group(0))
def my_code_to_generator(code):
code = re.sub("(?<=for)\d+(?=:)",sub_for,code)
code = re.sub("(?<=\s)[A-Za-z](?=\s)", sub_letter, code)
code = "def temp():\n " + code.replace("\n","\n ")
namespace = {}
exec(code,namespace)
return namespace["temp"]()
text = """
for 2:
{
a
for 3:
{
b
c
}
}""".replace("{","").replace("}","") #no curly braces in python!
>>> list(my_code_to_generator(text))
['a', 'b', 'c', 'b', 'c', 'b', 'c', 'a', 'b', 'c', 'b', 'c', 'b', 'c']
>>> "".join(my_code_to_generator(text))
'abcbcbcabcbcbc'
是的,我意識到這是一個非常不切實際和笨拙的解決方案,我不認爲這是最終答案,但直到有人發佈更好的答案,它可能會讓你得到一些結果。 :)
沒有理由期望具有不太強大工具的ad-hoc解決方案比使用爲您的任務設計的高級工具更簡單*。 – user2357112
但我需要將它集成到我的python項目中,該項目與這種序列一起工作。我能怎麼做?我需要使用什麼?什麼工具在談論?)))) –
獲取[pyparsing](http://pyparsing.wikispaces.com/)或其他一些解析器生成器,並自己寫一個解析器。 – user2357112