我正在編寫一些東西,以便分析帶有元素的字符串或數字的列表(或字典/元組)。但我有一個問題:我可以分析簡單的數字(從0到9),但不能分析其他數字。 這裏是我的代碼:語法NLTK數字
grammaire = nltk.CFG.fromstring("""
L -> OPEN CONTENT CLOSE
OPEN -> "["
CLOSE -> "]"
CONTENT -> Element Seq |
Seq -> | S Element Seq
S -> ","
Element -> Word | nombre | T | L | D
T -> "(" BeginTuple ")"
BeginTuple -> ElementTuple S ElementTuple EndTuple
EndTuple -> S ElementTuple |
ElementTuple -> nombre | T
D -> "{" BeginDic "}"
BeginDic -> ElementDic EndDic
EndDic -> S ElementDic EndDic |
ElementDic -> Key ":" Value
Key -> Word
Value -> nombre | T | L
Word -> "Bonjour" | "Aurevoir" | "Bye" | "Cya" | "Coucou" | " " | "Hello" | "Hi"
nombre -> chiffre | chiffre nombre
chiffre -> '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
""")
sent,res,elmt = "[{Bonjour:1,Hello:(1,2)}]",[],''
c = '()[]{}:,'
for x in sent:
if x in c:
if len(elmt) == 0:
res += [x,]
else:
#try: res += [int(elmt),] #si c'est un nombre on le transforme en int
#except: res += [elmt,]
res += [elmt,]
elmt = ""
res += [x,]
else:
elmt += x
print(res)
的importants線之初,以「CHIFFRE」和「農佈雷」。我究竟做錯了什麼?另外,我需要對字符串做同樣的事情(所以chiffre將會是'「a」|「b」|「c」...),而nombre將是相同的)。
我試圖把我的列表中的數字看作是Int,而不是Str,但它不起作用......(參見帶有try/except的註釋區域)。 Ofc然後我畫那棵樹。