Error to separate list of coordinates in Python - python

I have a file that contains 3 lists with pairs of coordinates. I would like to read the files and separate the first field as a name and the rest as coordinates. However, I don't know how to do this.
I am using the following code to read the txt file.
arquivo = open('dados_utm.txt', 'rt')
t = ' '
t1 = ' '
while t != '':
t = arquivo.readline()
t1 = t.split(' ')
print(t1)
Output:
['Poly', '"Pampulha"', '420545.,8039109.', '421826.,8039269.',
'424213.,8041682.', '424189.,8043000.', '424331.,8044861.',
'426457.,8047689.', '427082.,8047013.', '427713.,8044612.',
'427710.,8042703.', '428712.,8040642.', '428713.,8040196.',
'428790.,8039499.', '428356.,8038819.', '427844.,8039050.',
'426759.,8038697.', '426595.,8035314.', '427213.,8033950.',
'426558.,8030343.', '426113.,8030041.', '420041.,8030502.',
'419081.,8031438.', '419678.,8037604.', '420545.,8039109.\n']
['Poly',
'"Jacaré"', '425846.,8055763.', '424723.,8057841.',
'422398.,8058414.', '413568.,8058765.', '410307.,8060688.',
'403022.,8068114.', '402543.,8071067.', '403423.,8071846.',
'417134.,8073069.', '419408.,8074047.', '424638.,8068255.',
'429946.,8065755.', '430183.,8064351.', '433594.,8058696.',
'434290.,8058940.', '434296.,8057197.', '431016.,8051616.',
'430041.,8051612.', '428278.,8051122.\n']
['Poly', '"Patos"',
'437525.,7991091.', '439184.,7993615.', '435440.,8005422.',
'437290.,8006397.', '443981.,8000217.', '445662.,7995572.',
'448275.,7988217.', '446432.,7984918.', '438654.,7985476.',
'437525.,7991091.'] ['']
The second step is to separate the x and y coordinates for different variables. For this I am using the following code.
for i in t1[1,0]:
x = []
y = []
xy = t1.readline()
xy = xy.split(',')
x.append(float(xy[0]))
y.append(float(xy[1]))
print(x, y)
However I have the following error:
TypeError: list indices must be integers or slices, not tuple
txt file:
Poly "Pampulha" 420545.,8039109. 421826.,8039269. 424213.,8041682.
424189.,8043000. 424331.,8044861. 426457.,8047689. 427082.,8047013. 427713.,8044612. 427710.,8042703. 428712.,8040642. 428713.,8040196. 428790.,8039499. 428356.,8038819. 427844.,8039050. 426759.,8038697. 426595.,8035314. 427213.,8033950. 426558.,8030343. 426113.,8030041. 420041.,8030502. 419081.,8031438. 419678.,8037604. 420545.,8039109.
Poly "Jacaré" 425846.,8055763. 424723.,8057841. 422398.,8058414.
413568.,8058765. 410307.,8060688. 403022.,8068114. 402543.,8071067. 403423.,8071846. 417134.,8073069. 419408.,8074047. 424638.,8068255. 429946.,8065755. 430183.,8064351. 433594.,8058696. 434290.,8058940. 434296.,8057197. 431016.,8051616. 430041.,8051612. 428278.,8051122.
Poly "Patos" 437525.,7991091. 439184.,7993615. 435440.,8005422.
437290.,8006397. 443981.,8000217. 445662.,7995572. 448275.,7988217. 446432.,7984918. 438654.,7985476. 437525.,7991091.
what am I doing wrong?

You need more than one list because you're overwriting t1, you got that error from having [1, 0] after t1 in your for loop, t1 is a list so readline() won't work.
This should work and put coords as lists of tuples into dict t2 with the names as keys:
arquivo = open('dados_utm.txt', 'rt')
t = None
t1 = []
while t != '':
t = arquivo.readline()
t1.append(t.split(' '))
t2 = {}
for a in t1:
name = a.pop(0) + ' ' + a.pop(1)
t2[name] = []
for ele in a:
xy = ele.split(',')
x, y = float(xy[0]), float(xy[1])
t2[name].append((x, y))
print(t2)

You might want to think about pandas its a good library.
text = open('untitled.txt', 'rt').read()
lst = [item for item in text.split('\n') if item]
lst = [item.split(' ') for item in lst]
t2 = {}
for itr in lst:
name = ''.join(itr[0:2]).replace('"',' ')
t2[name] = {}
df = pd.DataFrame(map(lambda x: x.split(','),itr[2:]),columns=["X","Y"])
t2[name] = {
"X": df["X"].to_list(),
"Y": df["Y"].to_list()
}
print(t2)

Related

Output only specific items in a txt file according to strings from another list Python

I have a list of Strings:
myStrings = [Account,Type, myID]
I also have a txt file with numbers associated with these Strings, e.g:
[90: 'Account', 5: 'Type', 6: 'MyID', 8: 'TransactionNum', 9: 'Time']
How can I print only the numbers and strings in the txt file that are in myStrings. For example, since 'Time' is not in myStrings, I do not want to print it. I also would like to make this txt file a list
This should help u:
myStrings = ['Account','Type', 'myID']
f = open("D:\\Test.txt","r")
txt = f.read()
f.close()
txt = txt.replace('\n',' ')
txt = txt.split(',')
txtlst = []
for x in txt:
txtlst.append(x.split(':'))
numslst = [int(txtlst[i][0]) for i in range(len(txtlst))]
strlst = []
for i in txtlst:
for j in i:
try:
int(j)
except ValueError:
strlst.append(j.replace("'",""))
for x in range(len(strlst)):
strlst[x] = strlst[x].replace(' ','')
for x in range(len(strlst)):
if strlst[x] in myStrings:
print(numslst[x])
print(strlst[x])
Output:
90
Account
5
Type
After you have said that the file does not have [ & ] , could make it work like so :
import json
myStrings = ['Account','Type', 'myID']
with open('text-file.txt') as filename:
file_text = filename.read()
file_text_list = file_text.split(',')
file_text_dict = {}
for item in file_text_list:
k, v = item.split()
v = v.replace("'", "")
k = k.replace(":", "")
if v in myStrings:
file_text_dict[k] = v
print(file_text_dict) # output => {'90': 'Account', '5': 'Type'}
print(list(file_text_dict.values())) # output => ['Account', 'Type']

Lists in dictionary

I have a text file of format like this
10:45 a b c
x 0 1 2
y 4 5 6
z 7 8 9
I want to make x as key and 0,1,2 its value in the list.Same with y and z
while(1):
line = f.readline()
if time in line:
print (line)
L1.append(line)
for count,line in enumerate(f):
if (i < 3):
L1.append(line)
print ("Line{} : {}".format(count,line.strip()))
i=i+1
#print(L1)
for k in range(1):
print(L1[k])
test1 = L1[k]
a1 = test1.split()
print (a1[1])
dict = {a1[1]: L1[k] for a1[1] in L1[k]}
print (dict)
for k in range(1,3):
#print("hey")
print (L1[k]) #will list the single row
test = L1[k]
#print(test)
a = test.split()
print (a[0])
dict = {a[0]:L1[k] for a[0] in L1[k]}
print (dict)
Any idea what i am doing wrong here?
P.S. - I am new to python
You could try this:
my_dict = {}
lines = f.readLines()
lines.pop(0)
for line in lines:
line_list = line.split(' ')
key = line_list.pop(0)
my_dict.update({key: line_list})
This will accomplish what it is I think you need (assuming your text file is stored in the same directory and you replace 'test.txt' with your filename):
with open('test.txt', 'r') as values:
contents = values.read().strip().split()
new_dict = {}
i = 4
while i <= len(contents)-4:
new_dict.update({contents[i]: contents[i+1:i+4]})
i += 4
print(new_dict)
or this, if you want the values as integers:
with open('test.txt', 'r') as values:
contents = values.read().strip().split()
new_dict = {}
i = 4
while i <= len(contents)-4:
new_dict.update({contents[i]: [int(contents[i+1]),int(contents[i+2]),int(contents[i+3])]})
i += 4
print(new_dict)
Try this
import string
start_found = False
result_dict = {}
for line in open("stack1_input.txt", mode='r'):
if (line.startswith("10:45")):
start_found = True
continue
if start_found == True:
values = line.split()
if len(values) == 4:
result_dict[values[0]] = values[1:]
print (result_dict)

TypeError: can only concatenate list (not "int") to list [Using a Dictionary]

Essentially, I am creating a count by using a dictionary and everytime it sees a "1" in the text file, it adds one to the array.However, I keep getting an error
Letters = ["A","B,"C","D","E","F"]
d= {}
d["A"] = [0]
d["B"] = [0]
d["C"] = [0]
d["D"] = [0]
d["E"] = [0]
file = open('test1.txt','r')
for line in file:
line_array = line.strip("\n").split(",")
for x in range(5):
if line_array[x] == "1":
for y in Letters:
d[y][0] = d[y][0] + 1
BTW, the text file is formatted like this;
1,0,3,0,2
0,2,1,0,3
ETC
EDIT sorry, misworded
You never actually use your dictionary.
Letters= ["A","B","C","D","E"]
d= {key: 0 for key in Letters}
print(Letters)
file = open('test1.txt','r')
for line in file:
line_array = line.strip("\n").split(",")
for x in range(5):
if line_array[x] == "1":
for i, value in enumerate(Letters):
if i == x:
d[value] = d[value] + 1
#print(candidatescores) # No idea where this comes from

Hot skip special character in txt file python

I have some issues while reading txt files. What i have to do is read files ( about 360 ) and make a plot. Everything works except when there is a special character in my file such us: "". When my reading function finds that character it crashes. Is there any way to skip it? My code:
import os
import matplotlib.pyplot as plt
import numpy as np
i = 10
j = 0
X = []
Y = []
Z = []
k = 0
A = np.zeros([360,719])
for i in range(10,360,10):
X = []
Y = []
if len(str(i)) == 2:
data = open(dir + '\\150317_ScPONd_0%s_radio.txt'%i, 'r')
else:
data = open(dir + '\\150317_ScPONd_%s_radio.txt'%i, 'r')
z = data.readlines()
data.close()
for line in z:
if not line.startswith('$'):
data_2 = line.split('\t')
X.append(data_2[0])
Y.append(data_2[1])
A[j,:] = X
A[(j+1),:] = Y
And here is how my file looks like:
Is there any way to skip those "$" lines? Sorry for that picture, I have no idea how to attache It better.
Thaks to #user1753919 I have found an answer. If someone would be still interested in this, here is working code:
for i in range(10,360,10):
X = []
Y = []
if len(str(i)) == 2:
data = np.genfromtxt(dir + '\\150317_ScPONd_0%s_radio.txt'%i,skip_header = 12)
else:
data = np.genfromtxt(dir + '\\150317_ScPONd_%s_radio.txt'%i,skip_header = 12)
for line in data:
X.append(line[0])
Y.append(line[1])
A[j,:] = X
A[(j+1),:] = Y
plt.plot(A[j,:],A[(j+1),:],label = '{} K'.format(i))
plt.hold
j = j+2
genfromtxt is overkill.
np.loadtxt(file, comments='$')

List of named lists

I need to create a list of named lists in a python script.
What I want to do is create a mklist method that will take strings in a list and create lists named for each of the strings. So, from here:
a = "area"
for i in range(1, 37):
x = str(a) + str("%02d" % (i,))
' '.join(x.split())
I want to get the following:
area01 = []
area02 = []
area03 = []
area04 = []
area05 = []
area06 = []
area07 = []
area08 = []
area09 = []
area10 = []
area11 = []
area12 = []
area13 = []
area14 = []
area15 = []
area16 = []
area17 = []
area18 = []
area19 = []
area20 = []
area21 = []
area22 = []
area23 = []
area24 = []
area25 = []
area26 = []
area27 = []
area28 = []
area29 = []
area30 = []
area31 = []
area32 = []
area33 = []
area34 = []
area35 = []
area36 = []
Any advice? I can't seem to get it. Thanks!
E
This calls for either a list of lists:
area = [[] for i in range(37)]
Or a dict of lists:
area = {i: [] for i in range(1, 37)} # Python 2.7+
area = dict((i, []) for i in range(1, 37)) # Python 2.6 or earlier
Then you can access each item with:
area[1]
area[2]
...
area[36]
See this question.
a = "area"
for i in range(1, 37):
x = str(a) + str("%02d" % (i,))
locals()[x] = []
Or use globals() if you want the lists to be global.
That would give you empty list variables area01 to area36.
You should note though that just because it can be done, doesn't mean it should. A better/more readable solution would be:
area = [[] for i in range(37)]
(see John's solution)
Something like:
a = "area"
x = [ "%s%02d = []" % (a, i) for i in range(1,37) ]
print('\n'.join(x))
If you want your lists defined in the current Python session you sostitute the last line with
for i in range(0, 36):
exec(x[i])
And check with
print area01
print area35
Note however that this is not advisable

Categories

Resources