Why are Lists causing problems - python

So I am working on a certain code to modify a text file. When I use this function individually, it works perfectly
TextRotation.rotTextC("cv.txt")
But when I use it in batch as a list like this
def files_LTXT(pathF):
return glob.glob(pathF + "*" + ".txt")
for i in range (len(listFileTXT)):
TextRotation.rotTextC(listFileTXT[i])
IT gives the following error:
File "C:\Users\Administrator\PycharmProjects\openCV\TextRotation.py", line
9, in rotLineC
0
valueObj = int(lineStr[c1])
0.472917 0.713281 0.845833 0.376563
IndexError: string index out of range
Function rotLineC is as follows:
def rotLineC(lineStr, c1):
if len(lineStr) > 2:
valueObj = int(lineStr[c1])
print(valueObj)
valueXC = float(lineStr[(c1+2):(c1+10)])
valueYC = float(lineStr[(c1+11):(c1+19)])
valueW = float(lineStr[(c1+20):(c1+28)])
valueH = float(lineStr[(c1+29):(c1+37)])
# print(valueXC)
# print(valueYC)
# print(valueW)
# print(valueH)
nValueXC = round(1 - valueYC, 6)
nValueYC = round(valueXC, 6)
nValueW = round(valueH, 6)
nValueH = round(valueW, 6)
rotString = str(int(valueObj)) + " " + str(nValueXC) + " " + \
str(nValueYC) + " " + str(nValueW) + " " + str(nValueH)
print(str(nValueXC) + " " + str(nValueYC) + " " + str(nValueW) + " " + str(nValueH))
print(rotString)
return rotString
This function works fine!
for i in range (len(listFileJPG)):
ImageRotation.rotImage(listFileJPG[i])

Mind to include the / to the end of the path! (I am assuming a UNIX environment here)
If the path is 'dev/my_pat', for example, your function will fail. The path must end with a /. You can it to your function:
...
if pathF[-1] != '/':
return glob.glob(pathF + "/*.txt")
...
Also, do not iterate using indices, use the pythonic way!
for file in listFileTXT(my_path):
TextRotation.rotTextC(file)

Related

Openpyxl module: return weird value(not error) + hope to calculate

I wrote some codes trying to let the user be able to check the percentage of the money they spent(compared to the money they earned). Almost every step perform normally, until the final part.
a_c[('L'+row_t)].value return:
=<Cell 'Sheet1'.B5>/<Cell 'Sheet1'.J5>
yet I hope it should be some value.
Code:
st_column = st_column_r.capitalize()
row_s = str(a_c.max_row)
row_t = str(a_c.max_row + 1)
row = int(row_t)
a_c[('J'+row_t)] = ('=SUM(I2,J'+row_s+')') #總收入
errorprevention = a_c[('J'+row_t)].value
a_c[(st_column+row_t)] = ('=SUM('+(st_column+'2')+','+(st_column+row_s)+')')
a_c['L'+row_t].number_format = FORMAT_PERCENTAGE_00
if errorprevention != 0:
a_c[('L'+row_t)] = ('='+str(a_c[(st_column+row_t)])+'/'+str(a_c[('J'+row_t)]))
print('過往支出中,'+inputtype[st_column]+'類別佔總收入的比率為:'+a_c[('L'+row_t)].value)
Try changing the formula creation to;
a_c[('L' + row_t)].value = '=' + a_c[(st_column + row_t)].coordinate + '/' + a_c[('J' + row_t)].coordinate
or use an f string
a_c[('L' + row_t)].value = f"={a_c[(st_column + row_t)].coordinate}/{a_c[('J' + row_t)].coordinate}"

for-loop through a list with an if statement, only last position of list runs if statements

Here is my list, So models [0], names[0], mac_addresses[0] would all be required to calculate my mac address that I need
models = ["MR18","MR32", "MR18"]
names = ["David", "Bob", "Frank"]
mac_addresses = ["00:18:0A:2C:3D:5F", "00:18:0A:2d:3c:5F", "00:18:0A:2A:3B:5F"]
These are the functions that should run depending on which if statement is True.
def calc18(mac_address, name, mr):
#Mac Address Breakdown
print(name)
mac_calc = mac_address[:2]
mac_extractor_front = mac_address[2:6]
mac_extractor_back = mac_address[8:]
flag = True
First_Pos_Hex = first_hex_calc(mac_calc, mr, flag)
#Initial Mac Addresses
list_2_4.append(mac_address)
list_5.append(First_Pos_Hex + mac_extractor_front + mr_18_5ghz + mac_extractor_back)
flag = False
#First Time Calculation hex updated
hex_updater = first_hex_calc(mac_calc, mr, flag)
list_2_4.append(hex_updater + mac_extractor_front + mr_18_24ghz + mac_extractor_back)
list_5.append(hex_updater + mac_extractor_front + mr_18_5ghz + mac_extractor_back)
#Update self, after appending mac addresses
for i in range(15):
counter = i + 1
hex_updater = hex_calc(hex_updater, mr)
list_2_4.append(hex_updater + mac_extractor_front + mr_18_24ghz + mac_extractor_back)
list_5.append(hex_updater + mac_extractor_front + mr_18_5ghz + mac_extractor_back)
print(str(counter) + ") 2.4ghz: " + list_2_4[i] + "\t" + str(counter) + ") 5 Ghz: " + list_5[i] )
for i in range(len(list_2_4)):
writer(name, mac_address, list_2_4[i], list_5[i], i)
def calc32(mac_address, name):
#Mac Address Breakdown
mac_calc = mac_address[15:17]
mac_extractor_front = mac_address[:6]
mac_extractor_back = mac_address[8:15]
#Initial Mac Addresses
list_2_4.append(mac_extractor_front + mr_32_24ghz + mac_extractor_back + mac_calc)
list_5.append(mac_extractor_front + mr_32_5ghz + mac_extractor_back + mac_calc)
#Update self, after appending mac addresses
for i in range(15):
counter = i + 1
mac_calc = hex_calc(mac_calc, mr)
list_2_4.append(mac_extractor_front + mr_32_24ghz + mac_extractor_back + mac_calc)
list_5.append(mac_extractor_front + mr_32_5ghz + mac_extractor_back + mac_calc)
print(str(counter) + ") 2.4ghz: " + list_2_4[i] + "\t" + str(counter) + ") 5 Ghz: " + list_5[i] )
writer(name, mac_address, list_2_4[i], list_5[i], i)
Now I have this for-loop should iterate through each position in models, which would then check the if statements and execute a specific function
so, the first iteration models[0] which has "MR18" stored inside, then would check the if statements and execute calc18(),
after calc18() function finishes its execution would return to the for-loop and run the next iteration which would be models[1] which has "MR32", then again would check the if statements and execute calc32(). Then when calc32() finishes executing move on to models[2]
But in my case when I run the code, models[2] which represents "MR18" runs through the if statement, completely ignoring models[0] and models[1]
for num, mod in enumerate(models):
print(mod)
if mod == "MR18":
print("I have entered")
calc18(mac_addresses[num], names[num], mod)
if mod == "MR32":
print("I have entered 32")
calc32(mac_addresses[num], names[num])
If this is still confusing please let me know, I'm not sure if pictures are allowed, I can draw a visual example if that's allowed :(
As your code is not runnable on my system, I run a simpler version of code to illustrate that your code should indeed go through each element of models.
models = ["MR18","MR32", "MR18"]
names = ["David", "Bob", "Frank"]
mac_addresses = ["00:18:0A:2C:3D:5F", "00:18:0A:2d:3c:5F", "00:18:0A:2A:3B:5F"]
def calc18(mac_address, name, mr):
print("calc18 running")
print(mac_address)
print(name)
print(mr)
def calc32(mac_address, name):
print("calc32 running")
print(mac_address)
print(name)
for num, mod in enumerate(models):
print(num)
print(mod)
if mod == "MR18":
print("I have entered")
calc18(mac_addresses[num], names[num], mod)
if mod == "MR32":
print("I have entered 32")
calc32(mac_addresses[num], names[num])
produces:
0
MR18
I have entered
calc18 running
00:18:0A:2C:3D:5F
David
MR18
1
MR32
I have entered 32
calc32 running
00:18:0A:2d:3c:5F
Bob
2
MR18
I have entered
calc18 running
00:18:0A:2A:3B:5F
Frank
MR18
The code does go through each element of the list. The problem shouldn't be with the for loop.
I see writer in your code, of which you might be writing to a file. Do check if it is set to overwrite mode or append mode.

Script Loop through files in directory

I have the following code which creates the txt file I require from a shp.file with the data I need. I have a folder called profiles containing a few number of shape files named (profil1.shp, profil2.shp, profil3.shp etc.). I was wondering how to create a loop so that the script creates for each file a txt file with the same name (eg. for profil1.shp create profil1.txt, profil2.shp create profil2.txt and so on).
import ogr, os, sys, osr
os.chdir('..\profiles')
file = open('profil1.txt', 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open('profil1.shp', 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
edit: the code is returning a Could not open file.Photo of the folder containing the files and their respective names. Safe to assume I am doing something wrong.
import ogr, os, sys, osr,os.path
os.chdir = ('C:\Users\Andrei\Desktop\profil3')
l = os.listdir('C:\Users\Andrei\Desktop\profil3')
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
You can use os.listdir() to list the files and folders in the current directory.
This returns a list of all files in the current directory (or the directory given to it as parameter , if no parameter is specified it checks the current directory) .
Then you can check for files with the name ending with .shp using string.endswith() function and then use that to create your new files.
Example of a small portion -
import os , os.path
l = os.listdir()
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
At the end s1 would contain the file with extension as .txt .
Then you can do your logic on this file, and keep on doing like this.
Full code would look something like -
import ogr, os, sys, osr,os.path
os.chdir('..\profiles')
l = os.listdir()
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
A better way of openning files, etc is using with statement. Look up its tutorial here.

Python comma and divide an integer

def SetHP(self, hpPercentage, curHP, maxHP):
if not self.hpGauge.IsShow():
self.SetSize(200 + 7*self.nameLength, 70)
self.hpGauge.Show()
self.UpdatePosition()
self.hpGauge.SetPercentage(hpPercentage, 100)
strCurHP = str(curHP)
strMaxHP = str(maxHP)
self.broadCastHP.SetText(strCurHP + " / " + strMaxHP)
Example output is: 8993 / 18782
I see some questions like that, but all of them was about "float".
I want to make these integers like that:
8,9K / 18,7K
What is the "proper" way to do that?
Try this function:
def HPformat(str):
if len(str)==5:
newstr=str[0]+str[1] + ','+ str[2] + 'K'
return newstr
elif len(str)==4:
newstr=str[0]+','+ str[1] + 'K'
return newstr
And replace your final line of code with the function:
def SetHP(self, hpPercentage, curHP, maxHP):
if not self.hpGauge.IsShow():
self.SetSize(200 + 7*self.nameLength, 70)
self.hpGauge.Show()
self.UpdatePosition()
self.hpGauge.SetPercentage(hpPercentage, 100)
strCurHP = str(curHP)
strMaxHP = str(maxHP)
self.broadCastHP.SetText(HPformat(strCurHP) + " / " + HPformat(strMaxHP))
Also, if you don't want to add a new function you could just do:
def SetHP(self, hpPercentage, curHP, maxHP):
if not self.hpGauge.IsShow():
self.SetSize(200 + 7*self.nameLength, 70)
self.hpGauge.Show()
self.UpdatePosition()
self.hpGauge.SetPercentage(hpPercentage, 100)
strCurHP = str(curHP)
strMaxHP = str(maxHP)
newCurHP = strCurHP[0] + ',' + strCurHP [1] + 'K'
newMaxHP = strMaxHP[0] + strMaxHP[1] + ',' + strMaxHP[2] + 'K'
self.broadCastHP.SetText(newCurHP + " / " + newMaxHP)

Python: Expanding Complicated Tree DataStructure

I am exploring a data structure which get expands to sub-elements and resolves to a final element. But I only want to store top two levels.
Example: Lets say I start with New York which breaks into Bronx, Kings, New York, Queens, and Richmond as counties but then finally somehow they resolve to USA.
I am not sure if this is a good example but just to make it clear here is more clear explanation of the problem.
A (expands to) B,C,D -> B (expands to) K,L,M -> K resolves to Z
I initially wrote it in series of for loops and then use the recursion but in recursion I am loosing some of the elements that get expand and due to that I don't drill down each of the expanded element. I have put the both recursive version and non-recursive. I am looking for some advise on building this data structure, and what is the best way to do.
I call a data base query for every element in the expanded version which returns a list of items. Go until it resolves to single element. With out recursion I don't loose drilling all the way till the final element that others resolve to. But with recursion its not the same. I am also new to python so hopefully this is not a bad question to ask in a site like this.
returnCategoryQuery is a method that returns list of items by calling the database query.
With out recursion
#Dictionary to save initial category with the rest of cl_to
baseCategoryTree = {};
#categoryResults = [];
# query get all the categories a category is linked to
categoryQuery = "select cl_to from categorylinks cl left join page p on cl.cl_from = p.page_id where p.page_namespace=14 and p.page_title ='";
cursor = db.cursor(cursors.SSDictCursor);
for key, value in idTitleDictionary.iteritems():
for startCategory in value[0]:
#print startCategory + "End of Query";
categoryResults = [];
try:
categoryRow = "";
baseCategoryTree[startCategory] = [];
print categoryQuery + startCategory + "'";
cursor.execute(categoryQuery + startCategory + "'");
done = False;
while not done:
categoryRow = cursor.fetchone();
if not categoryRow:
done = True;
continue;
categoryResults.append(categoryRow['cl_to']);
for subCategoryResult in categoryResults:
print startCategory.encode('ascii') + " - " + subCategoryResult;
for item in returnCategoryQuery(categoryQuery + subCategoryResult + "'"):
print startCategory.encode('ascii') + " - " + subCategoryResult + " - " + item;
for subItem in returnCategoryQuery(categoryQuery + item + "'"):
print startCategory.encode('ascii') + " - " + subCategoryResult + " - " + item + " - " + subItem;
for subOfSubItem in returnCategoryQuery(categoryQuery + subItem + "'"):
print startCategory.encode('ascii') + " - " + subCategoryResult + " - " + item + " - " + subItem + " - " + subOfSubItem;
for sub_1_subOfSubItem in returnCategoryQuery(categoryQuery + subOfSubItem + "'"):
print startCategory.encode('ascii') + " - " + subCategoryResult + " - " + item + " - " + subItem + " - " + subOfSubItem + " - " + sub_1_subOfSubItem;
for sub_2_subOfSubItem in returnCategoryQuery(categoryQuery + sub_1_subOfSubItem + "'"):
print startCategory.encode('ascii') + " - " + subCategoryResult + " - " + item + " - " + subItem + " - " + subOfSubItem + " - " + sub_1_subOfSubItem + " - " + sub_2_subOfSubItem;
except Exception, e:
traceback.print_exc();
With Recursion
def crawlSubCategory(subCategoryList):
level = 1;
expandedList = [];
for eachCategory in subCategoryList:
level = level + 1
print "Level " + str(level) + " " + eachCategory;
#crawlSubCategory(returnCategoryQuery(categoryQuery + eachCategory + "'"));
for subOfEachCategory in returnCategoryQuery(categoryQuery + eachCategory + "'"):
level = level + 1
print "Level " + str(level) + " " + subOfEachCategory;
expandedList.append(crawlSubCategory(returnCategoryQuery(categoryQuery + subOfEachCategory + "'")));
return expandedList;
#Dictionary to save initial category with the rest of cl_to
baseCategoryTree = {};
#categoryResults = [];
# query get all the categories a category is linked to
categoryQuery = "select cl_to from categorylinks cl left join page p on cl.cl_from = p.page_id where p.page_namespace=14 and p.page_title ='";
cursor = db.cursor(cursors.SSDictCursor);
for key, value in idTitleDictionary.iteritems():
for startCategory in value[0]:
#print startCategory + "End of Query";
categoryResults = [];
try:
categoryRow = "";
baseCategoryTree[startCategory] = [];
print categoryQuery + startCategory + "'";
cursor.execute(categoryQuery + startCategory + "'");
done = False;
while not done:
categoryRow = cursor.fetchone();
if not categoryRow:
done = True;
continue;
categoryResults.append(categoryRow['cl_to']);
#crawlSubCategory(categoryResults);
except Exception, e:
traceback.print_exc();
#baseCategoryTree[startCategory].append(categoryResults);
baseCategoryTree[startCategory].append(crawlSubCategory(categoryResults));
Are you trying to lookup "Queens" and learn that it is in the USA? Have you tried encoding your tree in XML, and using lxml.etree to find an element and then use getpath to return the path in XPath format?
This would meaning adding a fourth top level to your tree, namely World, and then you would search for Queens and learn that the path to Queens is World/USA/NewYork/Queens. The answer to your question would always be the second item in the XPath.
Of course you could always just build a tree from the XML and use a tree search algorithm.

Categories

Resources