I have this code:
def findwordfiles(title):
name =[]
chekname =[]
title = title.strip()
found = 0
searchdir = '/Volumes/public/auryn/Marketing/Metadata/Auryn Reader'
for dirname, dirnames, filenames in os.walk(searchdir):
name = list(title)
i=0
j=0
for filename in filenames:
if filename.endswith((".docx")):
if ("Auryn_Reader_Meta_Data - " in filename):
hellname = filename.replace ("Auryn_Reader_Meta_Data - ","")
hellname = hellname.lower()
chekname = list(hellname)
for i in range (0, len(chekname)):
if (j < len(name)):
if name[j] == chekname[i]:
if j == (len(name)-1):
#raw_input("found! "+ title + " in file" + str(filename) )
target = os.path.join(os.getcwd(), "..")
shutil.copy2(os.path.join(dirname,filename), target)
found = 1
j = j+1
i=i+1
if( j/len(name) > 0.4):
if ( j/len(name) > matchpage):
closematch = str(filename)
matchpage = j/len(name)
i=0
j=0
if found == 0 :
# THE LINE BELOW GIVES ERROR
selection = raw_input ("no matches found, Closeset match = " + closematch +"match %age = " + str(matchpage) + " accept? (Y/N)")
if (selection == 'y' or selection == 'Y'):
target = os.path.join(os.getcwd(), "..")
shutil.copy2(os.path.join(dirname,closematch), target)
else:
print "Skipped copying!"
When i run this, I get an error: UnboundLocalError: local variable 'closematch' referenced before assignment on the marked line near the bottom.
What am I doing wrong?
You have not initialized closematch . The error indicates that the program never ran these lines :-
if( j/len(name) > 0.4):
if ( j/len(name) > matchpage):
closematch = str(filename)
i.e. it didn't even find a closematch.
Related
how to find sum of string containing operators '1+20/15-560*21' without using the BODMAS rule.
My code works well for single digit number while it fails when it comes to multiple digit number
i have attached my solution of single digit number
var = '1+2/3-4*5/5*2'
sumOfNum = var[0]
ch = '+-/*'
num = 0
value = ''
for i in range (1,len(var)):
if var[i] in ch:
inte = i
i = i+1
if var[inte] == '+':
sumOfNum = int(sumOfNum) + int(var[i])
if var[inte] == '/':
sumOfNum = int(sumOfNum) / int(var[i])
if var[inte] == '-':
sumOfNum = int(sumOfNum) - int(var[i])
if var[inte] == '*':
sumOfNum = int(sumOfNum) * int(var[i])
print(some)
i have tried and get the result
var = '1000+12/30-4*5/15000000*220+20000-15000000*220+20000+1000+12/30-4*5/15000000*220+20000-15000000*220+20000'
some = var[0]
inte = 0
ch = '+-/*'
num = 0
value = ''
lst =[]
for i in range (0,len(var)):
if var[i] in ch:
inte = i
lst.append(value)
lst.append(var[inte])
value = ''
else:
value = value+var[i]
i+=1
lst.append(value)
def sumOfAllNum(arg1, operand, arg2):
if operand == '+':
sumOfVal = arg1 + arg2
if operand == '-':
sumOfVal = arg1 - arg2
if operand == '*':
sumOfVal = arg1 * arg2
if operand == '/':
sumOfVal = arg1 / arg2
return sumOfVal
FinalSum = 0
sumOfVal = int(lst[0])
j = 0
for j in range(1,len(lst)):
if lst[j] in ch:
sumOfVal = sumOfAllNum(sumOfVal, lst[j], int(lst[j+1]))
print(sumOfVal)
I have this problem statement where I have a column of patterns that were if the first four bytes have date it should replace those four bytes to ccyy and the rest to N and zeros to Z's
eg. 20190045689 -> CCYYZZNNNNN
if space we need to consider the space as well.
66-7830956 -> NN-NNNZNNN
def patternGeneration(string):
x = re.findall("[\s0-9a-zA-Z]", string)
n = len(x)
j = 0
r = re.compile("\A[^(19|20)]")
y = list(filter(r.match, x))
b = len(y)
for i in range(0, b):
if y[i] == "0":
y[i] = 0
elif y[i] == " ":
y[i] = " "
else:
y[i] = "n"
print(convert(y))
for i in range(0, n):
if x[i] == "0":
x[i] = 0
j = j + 1
elif x[i] == " ":
x[i] = " "
j = j + 1
else:
x[i] = "n"
print(convert(x))
str1 = input("enter the string\t")
patternGeneration(str1)
#convert to new format
def convert(string):
# check for year
head = string[:4]
tail = string[4:]
if head.isnumeric():
if 1900 <= int(head) <= 2099:
head = "CCYY"
new_string = head + tail
return "".join(["Z" if x == "0" else "N" if x.isnumeric() else x for x in str(new_string)])
sample = "20196705540"
print(convert(sample))
#"CCYYNNZNNNZ"
sample = "66-7830956"
print(convert(sample))
#"NN-NNNZNNN"
Currently I'm writing a code where I want to ask motor values from motor controller using raspberry pi. However my code is throwing InvalidSyntax Error in else and elif statements. I've already read about if and elif statements in python, but I can't figure out mistake by myself. The code is below:
def motor_values():
while 1:
command_1 = '?A '+str(1)+' \r' #Asking first motor current
command_2 = '?A '+str(2)+' \r' #Asking second motor current
counter = 0
#First motor current
if counter = 0:
ser.write(command_1.encode()) #string to bytes
data_1 = ser.readline().decode().strip() #bytes to string
#Checking if data is received and extracting current value
if 'A=' in data_1:
value_1 = int(data_1.split('=')[1])
print("Motor Current(Channel 1): " + str((value_1) + " Ampers")
counter += 1
else:
print("Message is not received")
#Second motor current
elif counter == 1:
ser.write(command_2.encode()) #string to bytes
data_2 = ser.readline().decode().strip() #bytes to string
if 'A=' in data_2:
value_2 = int(data_2.split('=')[1])
print("Motor Current(Channel 2): " + str((value_2) + " Ampers")
counter += 1
else:
print("Message is not received")
else:
counter = 0
A few syntax errors here:
use == in the if clause condition
#First motor current
if counter == 0: #
remove one of the two ( in str((value_2)
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
print("Motor Current(Channel 2): " + str(value_2) + " Ampers")
you missed closing brace in print function
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
def tree_to_code(tree, feature_names):
tree_ = tree.estimators_
#print(tree_)
feature_name = [
feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature
]
print("def tree({}):".format(", ".join(feature_names)))
symptoms_present = []
def recurse(node, depth):
indent = " " * depth
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
print(name + " ?")
ans = input()
ans = ans.lower()
if ans == 'yes':
val = 1
else:
val = 0
if val <= threshold:
recurse(tree_.children_left[node], depth + 1)
else:
symptoms_present.append(name)
recurse(tree_.children_right[node], depth + 1)
else:
present_disease = print_disease(tree_.value[node])
print( "You may have " + present_disease )
red_cols = reduced_data.columns
symptoms_given = red_cols[reduced_data.loc[present_disease].values[0].nonzero()]
print("symptoms present " + str(list(symptoms_present)))
print("symptoms given " + str(list(symptoms_given)) )
confidence_level = (1.0*len(symptoms_present))/len(symptoms_given)
print("confidence level is " + str(confidence_level))
recurse(0, 1)
tree_to_code(clf,cols)
While changing decision tree code to random forest code,we got an attribute error at line 6 : for i in tree_.feature. Please help us to solve the error. It works using decision tree classifier but not using Random Forest Classifier .
List item
Why am i getting a syntax error on line 28? It seems like it should be just a normal line of code that prints the statement, but I keep getting a normal syntax error for it.
print('Welcome to the encryptor program.')
message = input('Enter the message you would like to encrypt.\n')
message = message.lower()
key = input('Enter the key you would like to use.\n')
def encrypt(k, m):
count = 0
keyCount = 0
fullCount = 0
newM = ''
while fullCount < len(m):
if (count) >= len(str(key)):
keyCount = 0
num = ord(m[count]) - 97
if m[count] != ' ':
add = int((str(k))[keyCount])
newNum = (num + add) % 26 + 97
new = chr(newNum)
newM += new
else:
newM += ' '
count += 1
fullCount += 1
keyCount += 1
print(newM)
encrypt(key, message)
def new_key(k):
newKey = int('1' + '0' * (((len(str(k))))-1) - key
The line after this
print('The new key to decrypt the message is', newKey)
new_key(key)