python里else显示无效语法_Python字典if/else无效语法

我不明白为什么第104行总是返回无效语法,有人能告诉我正确的方向吗?这跟我用伊莱夫的方式有关吗?抱歉,如果这是一个新手问题!在

第104行是中for项中的else语句工作dict.keys()printGrammar中的循环import sys

import string

from collections import defaultdict

#default length of 3

stringLength = 3

#get last argument of command line(file)

if len(sys.argv) == 1:

#get a length from user

try:

stringLength = int(input('Length? '))

filename = input('Filename: ')

except ValueError:

print("Not a number")

elif len(sys.argv) == 2:

#get a length from user

try:

stringLength = int(input('Length? '))

filename = sys.argv[1]

except ValueError:

print("Not a number")

elif len(sys.argv) == 3:

filename = sys.argv[2]

stringLength = sys.argv[1].split('l')[1]

else:

print("Invalid input!")

#get start symbol

with open(filename, "r") as grammar:

#read file

lines = grammar.readlines()

start = lines[0].split('=')[0]

start = start.replace(" ", "")

#checks

#print(stringLength)

#print(filename)

#print(start)

def str2dict(filename):

result = defaultdict(list)

with open(filename, "r") as grammar:

#read file

lines = grammar.readlines()

count = 0

#loop through

for line in lines:

#append info

line = line.rstrip()

result[line[0]].append(line.split('=')[1])

return result

workingDict = str2dict("Binary.txt")

print(workingDict)

def printGrammar(result):

sentenceList = []

workList = []

workList.append(start)

i = 0

firstNT = ""

#While the worklist is not empty:

while(len(workList) != 0):

#Get and delete one potential sentence s from the worklist.

symbol = workList.pop()

#If the | s | > N, continue.

if len(str(symbol).replace(" ", "")) > int(stringLength):

continue

else:

if str(symbol) in workingDict.keys():

#append the right derivation

for item in workingDict.get(symbol):

workList.append(list(item.replace(" ", "")))

#workList.append(str(workingDict.get(symbol)))

#add derivation

print(workingDict.keys())

#If s has no nonterminals, print s and continue.

for item in workingDict.keys():

print("test")

print(''.join(item))

if len(item) != 1:

continue

#if the element is in dictionary, dont print

elif ''.join(item) in workingDict.keys():

continue

print(symbol)

#if element is not in dictionary, print

else:

print("THIS IS A TERMINAL!!")

print(item)

#Choose the leftmost nonterminal NT.

print(workList)

#For all productions NT -> rhs:

#Replace NT in s with rhs; call it tmp.

#Store tmp on worklist.

return workList

print (printGrammar(workingDict))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值