AttributeError, What am I doing wrong here? - python

I have a program that I cannot call to run, where I try to call the linearSearch() def from spellCheck.py. Can someone help me understand why my code gives me a AttributeError? I do not understand why when calling initial.linearSearch(choice) won't give me anything.
spellCheck.py:
class SpellCheck():
def __init__(self):
try:
open("dictionary.txt", "r")
except FileNotFoundError:
print("Dictionary file not found")
else:
#store all elements in a list
dictionary = []
#open dictionary.txt
with open("dictionary.txt", "r") as f:
for line in f:
dictionary.append(line.strip())
def binarySearch(self, word):
steps = 0
low = 0
high = len(dictionary) - 1
while low <= high:
middle = (low + high) // 2
if(dictionary[middle] == word):
steps += 1
return (f"{bcolors.OKGREEN}Found {bcolors.BOLD}{word}{bcolors.ENDC}{bcolors.OKGREEN} after {steps} steps!{bcolors.ENDC}")
elif (dictionary[middle] < word):
steps += 1
low = middle + 1
else:
steps += 1
high = middle - 1
return(f"{bcolors.FAIL}The word {bcolors.BOLD}{word}{bcolors.ENDC}{bcolors.FAIL} wasn't found!{bcolors.ENDC}")
def linearSearch(word):
steps = 0
for i in range(len(dictionary)):
steps += 1
if dictionary[i] == self.word:
steps += 1
return(f"{bcolors.OKGREEN}Found {bcolors.BOLD}{self.word}{bcolors.ENDC}{bcolors.OKGREEN} after {steps - 1} steps!{bcolors.ENDC}")
return(f"{bcolors.FAIL}The word {bcolors.BOLD}{self.word}{bcolors.ENDC}{bcolors.FAIL} wasn't found!{bcolors.ENDC}")
#color coding for terminal
#source: https://stackoverflow.com/a/287944
#either True or False
class bcolors:
BOLD = '\033[1m'
OKGREEN = '\033[92m'
FAIL = '\033[91m'
ENDC = '\033[0m'
YELLOW = '\033[93m'
#debug statement
#if debug == True:
#print(f"Debug Colors:\n{BOLD}BOLD{ENDC}\n{OKGREEN}OKGREEN{ENDC}\n{FAIL}FAIL{ENDC}\n{YELLOW}YELLOW{ENDC}")
#end of color codes
main.py
from spellCheck import SpellCheck
#from spellCheck import bcolors
def main():
choice = input("Enter the word to look for:\n> ")
initial = SpellCheck()
initial.__init__()
initial.linearSearch(choice)
main()
Here is the output of the terminal:
Enter the word to look for:
> apple
Traceback (most recent call last):
File "main.py", line 11, in <module>
main()
File "main.py", line 8, in main
initial.linearSearch(choice)
AttributeError: 'SpellCheck' object has no attribute 'linearSearch'

binarySearch(self, word) and linearSearch(word) are the functions of __init__
that's why you are not getting any error on initial.linearSearch(choice).
If you want them to be separate functions of SpellCheck() then unindent them.

Related

ValueError: substring not found on lip reading code

This is what I have gotten while trying to run step 3 of this source code:
https://github.com/carykh/lazykh
Error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\lazykh-main\code\scheduler.py", line 93, in
OS_nextIndex = originalScript.index(wordString,OS_IndexAt)+len(wordString)
ValueError: substring not found
Code:
import argparse
import os.path
import json
import numpy as np
import random
def addPhoneme(p, t):
global prevPhoneme
global f
if p != prevPhoneme:
strings[4] += (str.format('{0:.3f}', t)+",phoneme,"+p+"\n")
prevPhoneme = p
def pickNewPose(t):
global pose
global prevPose
global POSE_COUNT
global prevPhoneme
global f
newPose = -1
while newPose == -1 or newPose == pose or newPose == prevPose:
newPose = int(random.random()*POSE_COUNT)
prevPose = pose
pose = newPose
strings[3] += (str.format('{0:.3f}', t)+",pose,"+str(pose)+"\n")
prevPhoneme = "na"
strings = [""]*5
POSE_COUNT = 5
emotions = {}
emotions["explain"] = 0
emotions["happy"] = 1
emotions["sad"] = 2
emotions["angry"] = 3
emotions["confused"] = 4
emotions["rq"] = 5
mouthList = [["aa","a"],["ae","a"],["ah","a"],["ao","a"],["aw","au"],
["ay","ay"],["b","m"],["ch","t"],["d","t"],["dh","t"],
["eh","a"],["er","u"],["ey","ay"],["f","f"],["g","t"],
["hh","y"],["ih","a"],["iy","ay"],["jh","t"],["k","t"],
["l","y"],["m","m"],["n","t"],["ng","t"],["ow","au"],
["oy","ua"],["p","m"],["r","u"],["s","t"],["sh","t"],
["t","t"],["th","t"],["uh","u"],["uw","u"],["v","f"],
["w","u"],["y","y"],["z","t"],["zh","t"],
["oov","m"]] # For unknown phonemes, the stick figure will just have a closed mouth ("mmm")
mouths = {}
for x in mouthList:
mouths[x[0]] = x[1]
ENDING_PHONEME = "m"
STOPPERS = [",",";",".",":","!","?"]
parser = argparse.ArgumentParser(description='blah')
parser.add_argument('--input_file', type=str, help='the script')
args = parser.parse_args()
INPUT_FILE = args.input_file
f = open(INPUT_FILE+".txt","r+")
originalScript = f.read()
f.close()
f = open(INPUT_FILE+".json","r+")
fileData = f.read()
f.close()
data = json.loads(fileData)
WORD_COUNT = len(data['words'])
pose = -1
prevPose = -1
prevPhoneme = "na"
emotion = "0"
pararaph = 0
image = 0
OS_IndexAt = 0
pickNewPose(0)
strings[1] += "0,emotion,0\n"
strings[0] += "0,paragraph,0\n"
strings[2] += "0,image,0\n"
strings[4] += "0,phoneme,m\n"
for i in range(WORD_COUNT):
word = data['words'][i]
if "start" not in word:
continue
wordString = word["word"]
timeStart = word["start"]
OS_nextIndex = originalScript.index(wordString,OS_IndexAt)+len(wordString)
if "<" in originalScript[OS_IndexAt:]:
tagStart = originalScript.index("<",OS_IndexAt)
tagEnd = originalScript.index(">",OS_IndexAt)
if OS_nextIndex > tagStart and tagEnd >= OS_nextIndex:
OS_nextIndex = originalScript.index(wordString,tagEnd)+len(wordString)
nextDigest = originalScript[OS_IndexAt:OS_nextIndex]
if "\n" in nextDigest and data['words'][i-1]['case'] != 'not-found-in-audio' and (prevPhoneme == "a" or prevPhoneme == "f" or prevPhoneme == "u" or prevPhoneme == "y"):
addPhoneme("m", data['words'][i-1]["end"])
"""print(wordString)
print(str(OS_IndexAt)+", "+str(OS_nextIndex))
print(nextDigest)
print("")"""
pickedPose = False
for stopper in STOPPERS:
if stopper in nextDigest:
pickNewPose(timeStart)
pickedPose = True
if "<" in nextDigest:
leftIndex = nextDigest.index("<")+1
rightIndex = nextDigest.index(">")
emotion = emotions[nextDigest[leftIndex:rightIndex]]
strings[1] += (str.format('{0:.3f}', timeStart)+",emotion,"+str(emotion)+"\n")
prevPhoneme = "na"
if "\n\n" in nextDigest:
pararaph += 1
image += 1 # The line of the script advances 2 lines whenever we hit a /n/n.
strings[0] += (str.format('{0:.3f}', timeStart)+",paragraph,"+str(pararaph)+"\n")
prevPhoneme = "na"
if "\n" in nextDigest:
image += 1
strings[2] += (str.format('{0:.3f}', timeStart)+",image,"+str(image)+"\n")
prevPhoneme = "na"
if not pickedPose:
pickNewPose(timeStart) # A new image means we also need to have a new pose
phones = word["phones"]
timeAt = timeStart
for phone in phones:
timeAt += phone["duration"]
phoneString = phone["phone"]
if phoneString == "sil":
truePhone = "m"
else:
truePhone = mouths[phoneString[:phoneString.index("_")]]
if len(truePhone) == 2:
addPhoneme(truePhone[0], timeAt-phone["duration"])
addPhoneme(truePhone[1], timeAt-phone["duration"]*0.5)
else:
addPhoneme(truePhone, timeAt-phone["duration"])
OS_IndexAt = OS_nextIndex
f = open(INPUT_FILE+"_schedule.csv","w+")
for i in range(len(strings)):
f.write(strings[i])
if i < len(strings)-1:
f.write("SECTION\n")
f.flush()
f.close()
print(f"Done creating schedule for {INPUT_FILE}.")
The
ValueError: substring not found
occurs when you try to find the index of a substring in a string which does not contain it in the specified (or default) section, using the index function.
The index method takes 3 parameters:
value
start
end
and it searches for the value between start and end.
So, the error occurred because the substring was not found in the section where it was searched for. The line of
OS_nextIndex = originalScript.index(wordString,tagEnd)+len(wordString)
searches for wordString, starting from tagEnd and searches for the likes of
<span>yourwordstring</span>
, but in your case it was not found. You can do one of the following to solve the issue:
you can fix your input if it should always have a match for the search
you can handle the error when the index throws the error
you can use find instead, see https://bobbyhadz.com/blog/python-valueerror-substring-not-found
Note that find also has three parameters, as you can read from https://www.w3schools.com/python/ref_string_find.asp

bluepy.btle.BTLEManagementError: Failed to execute management command 'le on' (code: 20, error: Permission Denied)

I utilised and modified the code that is shown below, from https://www.instructables.com/Monitor-and-Record-Temperature-With-Bluetooth-LE-a/
The problem I run into is that the device seems to be blocking me from accessing it's values, although I am unsure of this.
Here is my code:
from bluepy.btle import Scanner, DefaultDelegate
import time
import struct
SENSOR_ADDRESS = [""ec:fe:4e:12:b8:72""]
class DecodeErrorException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
print("Discovered device", dev.addr)
elif isNewData:
print("Received new data from", dev.addr)
scanner = Scanner().withDelegate(ScanDelegate())
ManuDataHex = []
ReadLoop = True
try:
while (ReadLoop):
devices = scanner.scan(2.0)
ManuData = ""
for dev in devices:
entry = 0
TempData = 0
for saddr in SENSOR_ADDRESS:
entry += 1
if (dev.addr == saddr):
CurrentDevAddr = saddr
for (adtype, desc, value) in dev.getScanData():
if (desc == "Manufacturer"):
ManuData = value
if (ManuData == ""):
print("No data received, end decoding")
continue
print(ManuData)
for i, j in zip(ManuData[::2], ManuData[1::2]):
ManuDataHex.append(int(i+j, 16))
if ((ManuDataHex[0] == 0x85) and (ManuDataHex[1] == 0x00)):
print("Header byte 0x0085 found")
else:
print("Header byte 0x0085 not found, decoding stop")
continue
idx = 7
print("TotalLen: " + str(len(ManuDataHex)))
while idx < len(ManuDataHex):
if (ManuDataHex[idx] == 0x43):
idx += 1
TempData = ManuDataHex[idx]
TempData += ManuDataHex[idx+1] * 0x100
TempData = TempData * 0.0625
idx += 2
else:
idx += 1
print("Device Address: " + CurrentDevAddr)
print("Temp Data: " + str(TempData))
ReadLoop = False
except DecodeErrorException:
pass
The exception is as follows:
Traceback (most recent call last):
File "/home/pi/Desktop/lameteo/print.py", line 31, in
devices = scanner.scan(2.0)
File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 852, in scan
self.start(passive=passive)
File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 790, in start
self._mgmtCmd("le on")
File "/usr/local/lib/python3.7/dist-packages/bluepy/btle.py", line 312, in _mgmtCmd
raise BTLEManagementError("Failed to execute management command '%s'" % (cmd), rsp)
bluepy.btle.BTLEManagementError: Failed to execute management command 'le on' (code: 20, error: > Permission Denied)
If you have any expertise in this area I would greatly appreciate your help.
use sudo infront when you call the script in your terminal

obfuscation of a text file using python - by reversing the words and inserting a specific number of random characters between them

Beginner Coding problem I am supposed to write a code that reverses the contents of a file and then inserts a number of random characters based on a strength the user chooses. It then creates a new file containing the obstructed file.
For example, if the user chooses strength = 2, it will insert 2 random characters between each letter in the text file: The cat sits ---> sgyt6gilns t7faxdc e3dh1kT
Right now my program inserts too many characters in between and I can't figure out why.
This is what it's doing:
input: CAT
Output of strength = 1: TeAEADQoC
import string
import random
def getRandomChar():
alpha = string.ascii_letters + string.digits
return random.choice(alpha)
def randomString(EncrypStrength):
count = 0
result = ''
while count < len(EncrypStrength):
result += getRandomChar()
count += 1
return result
def ReverseString(OrigFile):
return OrigFile[::-1]
def LineEncrypt(line, EncrypStrength):
EncrypStrength = ReverseString(line)
index = 0
newline = EncrypStrength[index]
index += 1
while index < len(EncrypStrength):
newline += randomString(EncrypStrength)
newline += EncrypStrength[index]
index += 1
return newline
def main():
OrigFile =input('Original File Name:')
EncryptedFile = input("obfuscated File Name:")
EncrypStrength = int(input('Enter the Encryption Strength:'))
Orig = open(OrigFile, 'r')
Encrypted = open(EncryptedFile, 'w')
line = Orig.readline()
while line!= '':
encryptLine = LineEncrypt(line, EncrypStrength)
Encrypted.write(encryptLine +"\n")
line = Orig.readline()
Orig.close()
Encrypted.close()
if __name__=="__main__":
main()
In Line Encrypt method you are using incorrectly Encrypt Strength, you are overriding the number of characters to put as EncryptStrength with reversed line.
def LineEncrypt(line, EncrypStrength):
reversedString = ReverseString(line)
index = 0
newline = reversedString[index]
index += 1
while index < len(reversedString):
newline += randomString(EncrypStrength)
newline += reversedString[index]
index += 1
You are confusing EncrypStrength and overriding it as Ritesh mentioned.
Here is the full corrected code, I hope it will work as you expected.
import string
import random
def getRandomChar():
alpha = string.ascii_letters + string.digits
return random.choice(alpha)
def randomString(EncrypStrength):
count = 0
result = ''
while count < EncrypStrength:
result += getRandomChar()
count += 1
return result
def ReverseString(OrigFile):
return OrigFile[::-1]
def LineEncrypt(line, EncrypStrength):
RevStr = ReverseString(line)
index = 0
newline = RevStr[index]
index += 1
while index < len(RevStr):
newline += randomString(EncrypStrength)
newline += RevStr[index]
index += 1
return newline
def main():
OrigFile =input('Original File Name:')
EncryptedFile = input("obfuscated File Name:")
EncrypStrength = int(input('Enter the Encryption Strength:'))
Orig = open(OrigFile, 'r')
Encrypted = open(EncryptedFile, 'w')
line = Orig.readline()
while line!= '':
encryptLine = LineEncrypt(line, EncrypStrength)
Encrypted.write(encryptLine +"\n")
line = Orig.readline()
Orig.close()
Encrypted.close()
if __name__=="__main__":
main()

How to fix TypeError: 'intancemethod' object is unscriptable error in Python/Fiji

I'm trying to get Fiji to run a contrasting function on a set of images for analysis. but whenever I try to run the file I get an error when I try to index the histogram object. The contrasting code is supposed to mimic the autothresholding function which is usable through Fiji. I have already tried to use IJ.run(imp, "Enhance Contrast", "saturated=0.02), but it doesn't get as good results as the autothreshold.
dc = DirectoryChooser("Choose a folder")
folder = dc.getDirectory()
for filename in os.listdir(folder):
if filename.endswith(".tif"):
print "Processing", filename
imp = IJ.openImage(os.path.join(folder, filename))
if imp is None:
print "Could not open image from file:", filename
continue
IJ.run(imp,"8-bit","")
at = 0
AT = 5000
cal = imp.getCalibration()
imp.setCalibration(None)
stats = imp.getStatistics()
imp.setCalibration(cal)
limit = int(stats.pixelCount/10)
histogram = stats.histogram
if at < 10:
at = AT
else:
at /= 2
threshold = int(stats.pixelCount/at)
i = -1
found = False
count = 0
while True:
i += 1
count = histogram[i]
if count > limit:
count = 0
found = count > threshold
if found or i >= 255:
break
hmin = i
i = 256
while True:
i -= 1
count = histogram[i]
if count > limit:
count = 0
found = count > threshold
if found or i < 1:
break
hmax = i
else:
print "Ignoring", filename
Traceback (most recent call last):
File "C:\Users\jacob\Documents\School\PytonTest.py", line 41, in <module>
count = histogram[i]
TypeError: 'instancemethod' object is unsubscriptable
at org.python.core.Py.TypeError(Py.java:265)
at org.python.core.PyObject.__finditem__(PyObject.java:687)
at org.python.core.PyObject.__getitem__(PyObject.java:755)
at org.python.pycode._pyx0.f$0(C:/Users/jacob/Documents/School/PytonTest.py:11)
at org.python.pycode._pyx0.call_function(C:/Users/jacob/Documents/School/PytonTest.py)
at org.python.core.PyTableCode.call(PyTableCode.java:171)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1614)
at org.python.core.__builtin__.eval(__builtin__.java:497)
at org.python.core.__builtin__.eval(__builtin__.java:501)
at org.python.util.PythonInterpreter.eval(PythonInterpreter.java:259)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:57)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:31)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at org.scijava.script.ScriptModule.run(ScriptModule.java:160)
at org.scijava.module.ModuleRunner.run(ModuleRunner.java:168)
at org.scijava.module.ModuleRunner.call(ModuleRunner.java:127)
at org.scijava.module.ModuleRunner.call(ModuleRunner.java:66)
at org.scijava.thread.DefaultThreadService$3.call(DefaultThreadService.java:238)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Change how you get the histogram to the following - this should solve your problem:
test = imp.getProcessor()
histogram = test.getHistogram()

While reading a text file sequentially how to go back to a particular line and start again from there

Newbie alert!
Path = "C:/Users/Kailash/Downloads/Results_For_Stride-Table.csv"
counter_start = 0
counter_end = 0
num_lines = len(open(Path).read().splitlines())
print("num_lines = ", num_lines)
with open(Path, "r") as f:
for lines in f:
print("lines = ", lines)
counter_end += 1
Stride_Length = lines.split(", ")
Previous_Sum = distances
Previous_Sum_GCT = Total_GCT
Previous_Heading = Sum_Heading
GCT = float(Stride_Length[2])
Total_GCT += GCT
print("Total_GCT = ", Total_GCT)
distances += float(Stride_Length[3])
print("distances = ", distances)
Sum_Heading += float(Stride_Length[7])
print("Sum_Heading = ", Sum_Heading)
print("counter_end = ", counter_end)
if(GCT == 0.00):
distances = 0
counter_end = 0
if distances > 762:
print("counter_end = ", counter_end)
counter_start = counter_end
lines_test = f.readlines()
print("counter start = ", counter_start)
print("move = ", lines_test[counter_start-counter_end-1])
print("Distance is above 762")
distances = 0
I want to know how to go back to a particular line in a file and start reading from there again in python. when I try to use f.readlines() in the last but 5th line in my code, the processing stops right there.
You can build a list of line start positions (file offsets), and then use file.seek(line_offsets[n]) to go back to the nth line (counting from zero). After that you can read the line (and those following it sequentially) once again.
Here's example code showing building such a list incrementally:
filepath = "somefile"
line_offsets = []
with open(filepath, "r") as file:
while True:
posn = file.tell()
line = file.readline()
if not line: # end-of-file?
break
line_offsets.append(posn) # Remember where line started.
""" Process line """
... code above ...
for line in data:
if counter_end<= <line to stop at>:
continue
counter_end += 1
...
a = linecache.getlines('D:/aaa.txt')[5]
import linecache
a = linecache.getlines('D:/aaa.txt')[5]

Categories

Resources