TypeError: 'type' object is not subscriptable. How can I get this to remove an array from a 2d array? - python

I have had a look at answers to similar questions but I just can't make this work. I am quite new to python.
def read():
set = []
f = open("error set 1.txt", "r")
replace = f.read()
f.close()
f = open("Test1_Votes.txt", "w")
replaced = replace.replace(",", "")
f.write(replaced)
f.close()
f = open("Test1_Votes.txt", "r")
for line in f:
ballot = []
for ch in line:
vote = ch
ballot.append(vote)
print (ballot)
set.append(ballot)
"""print(set)"""
remove()
def remove():
for i in range (70):
x = i - 1
check = set[x]
if 1 not in check:
set.remove[x]
print(set)
The error is line 37, check = set[x]
I'm unsure of what is actually causing the error

In the remove function, you have not defined set. So, python thinks it's the built-in object set, which is actually not subscriptable.
Pass your object to the remove function, and, preferably, give it another name.

Your remove function cant "see" your set variable (which is list, avoid using reserved words as variable name), because its not public, its defined only inside read function.
Define this variable before read function or send it as input to remove function, and it should be working.
def read():
set = []
f = open("error set 1.txt", "r")
replace = f.read()
f.close()
f = open("Test1_Votes.txt", "w")
replaced = replace.replace(",", "")
f.write(replaced)
f.close()
f = open("Test1_Votes.txt", "r")
for line in f:
ballot = []
for ch in line:
vote = ch
ballot.append(vote)
print (ballot)
set.append(ballot)
"""print(set)"""
remove(set)
def remove(set):
for i in range (70):
x = i - 1
check = set[x]
if 1 not in check:
set.remove(x)
print(set)

Related

How do I make a proper referencing of variable in python function?

def main():
try:
with open("actions.txt", "r") as infile:
line = infile.readlines()
except FileNotFoundError:
exit(f"tried to open file {actions.txt}, file not fount")
a = 20
aN = 0
Set = set()
while line != "":
line_1 = line.rstrip("\n")
line_1 = line_1.rsplit(", ")
print(line_1)
if a != 0:
if line_1[2] == "a" and int(line_1[3]) <= a and aN <= 2:
aN += 1
a = a - int(line_1[3])
Set.add(f"a's: {line_1[0]} {line_1[3]} ,")
print(Set)
The main idea of this code is to read a txt file containing information about a variable a, if it's found in the code, then it does some operation with that variable and outputs itself.
my code worked w/o an introduction of a "main" function. But i have to read the file using a def main(). I have no output as the file can't be read due to the improper referencing of variable. Hope for ur help

Error "fix_county_string(s) NameError: name 's' is not defined." I am trying to fix all counties in the file

Consider:
def fix_county_string(s):
""" Insert Docstring """
fp = open("michigan_COVID_08_24_21.txt", "r")
fp.readline()
for line in fp:
county = line[24:43]
x = county.split()
t = x.pop(-1)
s = x.append("County")
return s
fix_county_string(s)
The parameter is s, a string. Every county name ends with the places; if it correctly ends in places, do nothing (simply return s). Otherwise, correct the ending word to be place. Specifically, if not, fix it.
Use:
def fix_county_string():
""" Insert Docstring """
fp = open("michigan_COVID_08_24_21.txt", "r")
s = ''
for line in fp:
county = line[24:43]
x = county.split()
t = x.pop(-1)
x.append("County")
s += line + ' '.join(x)
return s
s = fix_county_string()
I think this is what you are trying to do. You can write back the output in a file.

self modifying python script

I want to create python script which can modify code in that script itself using Python Language Services or using any other way.
e.g. A script which keep track of its count of successfull execution
import re
COUNT = 0
def updateCount():
# code to update second line e.g. COUNT = 0
pass
if __name__ == '__main__':
print('This script has run {} times'.format(COUNT))
updateCount()
On successful execution of this script code should get changed to
import re
COUNT = 1
def updateCount():
# code to update second line e.g. COUNT = 0
pass
if __name__ == '__main__':
print('This script has run {} times'.format(COUNT))
updateCount()
Simple approach came to my mind was to open __file__ in write mode and do requried modification using reguler expessions etc. But that did not work I got exception io.UnsupportedOperation: not readable. Even if this approach would be working then it would be very risky because it can spoil my whole script. so I am looking for solution using Python Language Services.
Yes, you can use the language services to achieve self-modification, as in following example:
>>> def foo(): print("original foo")
>>> foo()
original foo
>>> rewrite_txt="def foo(): print('I am new foo')"
>>> newcode=compile(rewrite_text,"",'exec')
>>> eval(newcode)
>>> foo()
I am new foo
So, by new dynamically generated code you can replace stuff contained in the original source file, without modifying the file itself.
A python script is nothing more than a text file. So, you are able to open it as an external file and read & write on that. (Using __file__ variable you can get the exact name of your script):
def updateCount():
fin = open(__file__, 'r')
code = fin.read()
fin.close()
second_line = code.split('\n')[1]
second_line_parts = second_line.split(' ')
second_line_parts[2] = str(int(second_line_parts[2])+1)
second_line = ' '.join(second_line_parts)
lines = code.split('\n')
lines[1] = second_line
code = '\n'.join(lines)
fout = open(__file__, 'w')
fout.write(code)
fout.close()
#kyriakosSt's answer works but hard-codes that the assignment to COUNT must be on the second line, which can be prone to unexpected behaviors over time when the line number changes due to the source being modified for something else.
For a more robust solution, you can use lib2to3 to parse and update the source code instead, by subclassing lib2to3.refactor.RefactoringTool to refactor the code using a fixer that is a subclass of lib2to3.fixer_base.BaseFix with a pattern that looks for an expression statement with the pattern 'COUNT' '=' any, and a transform method that updates the last child node by incrementing its integer value:
from lib2to3 import fixer_base, refactor
COUNT = 0 # this should be incremented every time the script runs
class IncrementCount(fixer_base.BaseFix):
PATTERN = "expr_stmt< 'COUNT' '=' any >"
def transform(self, node, results):
node.children[-1].value = str(int(node.children[-1].value) + 1)
return node
class Refactor(refactor.RefactoringTool):
def __init__(self, fixers):
self._fixers = [cls(None, None) for cls in fixers]
super().__init__(None)
def get_fixers(self):
return self._fixers, []
with open(__file__, 'r+') as file:
source = str(Refactor([IncrementCount]).refactor_string(file.read(), ''))
file.seek(0)
file.write(source)
Demo: https://repl.it/#blhsing/MushyStrangeClosedsource
This will edit the module level variables defined before _local_config. Later, process an update to the dictionary, then replace the line when iterating over the source file with the new _local_config values:
count = 0
a = 0
b = 1
c = 1
_local_config = dict(
filter(
lambda elem: (elem[0][:2] != "__") and (str(elem[1])[:1] != "<"),
globals().items(),
),
)
# do some stuff
count += 1
c = a + b
a = b
b = c
# update with new values
_local_config = dict(
filter(
lambda elem: elem[0] in _local_config.keys(),
globals().items(),
)
)
# read self
with open(__file__, "r") as f:
new_file = ""
for line in f.read().split("\n"):
for k, v in _local_config.items():
search = f"{k} = "
if search == line[: len(k) + 3]:
line = search + str(v)
_local_config.pop(k)
break
new_file += line + "\n"
# write self
with open(__file__, "w") as f:
f.write(new_file[:-1])

Why does my function fail to create lists?

I am trying to create 5 lists out of 1 data file, the error I keep getting states that "airlines is not defined", yet it is the first thing I define in the function, how is this possible? What should I do to correctly create a list of airlines, arrival times, departure times, prices, and flight number?
USAir,1269,6:15,10:57,210
Delta,5138,16:20,22:10,212
UNITED,6001,14:12,20:50,217
Delta,5054,12:30,20:22,227
UNITED,5949,9:30,14:43,264
JetBlue,1075,17:00,20:06,280
Delta,1263,6:00,11:30,282
Delta,3824,9:00,14:45,282
USAir,1865,16:55,21:33,300
USAir,3289,18:55,23:41,300
USAir,1053,8:00,13:02,300
USAir,2689,12:55,18:09,300
USAir,3973,9:25,14:00,302
USAir,3267,11:30,16:13,302
USAir,3609,13:25,18:28,302
USAir,3863,15:35,20:54,302
USAir,3826,17:45,23:19,302
USAir,1927,7:00,12:53,302
Delta,3601,12:00,17:29,307
Delta,4268,7:15,12:46,307
UNITED,4676,6:00,10:45,321
UNITED,4103,11:00,16:16,321
USAir,3139,11:51,16:29,332
JetBlue,475,7:30,10:42,340
USAir,3267,11:30,18:15,367
UNITED,2869,16:55,21:33,406
UNITED,2865,6:15,10:57,406
UNITED,2729,8:00,13:02,406
UNITED,2645,7:00,12:53,445
and the code I am using is
def getFlights():
airlines = []
flightNums = []
depTimes = []
arriveTimes = []
prices = []
fname = input("Enter name of data file: ")
infile = open(fname, 'r')
line = infile.readline()
line = line.strip()
while line != "":
line = line.strip()
airline, flightNum, depTime, arriveTime, price = line.split(',')
airlines.append(airline)
flightNums.append(flightNum)
depTimes.append(depTime)
arriveTimes.append(arriveTime)
prices.append(price)
line = infile.readline()
line = line.strip()
infile.close()
return airlines, flightNums, depTimes, arriveTimes, prices
getFlights()
print(airlines, flightNums, depTimes, arriveTimes, prices)
Local variables inside a function are not accessible outside of the function call. If you want to use the returned values of getFlights you must assign them to variables in the calling context.
(airlines, flightNums, depTimes, arriveTimes, prices) = getFlights()
print(airlines, flightNums, depTimes, arriveTimes, prices)
What b4hand has said is correct, however, the Pythonic way of doing this is using csv.reader and a with statement, eg:
import csv
filename = input('Enter filename: ')
with open(filename, 'rb') as fin:
csvin = csv.reader(fin)
airlines, flightNums, depTimes, arriveTimes, prices = zip(*csvin)

Parsing Input File in Python

I have a plain text file with some data in it, that I'm trying to open and read using a Python (ver 3.2) program, and trying to load that data into a data structure within the program.
Here's what my text file looks like (file is called "data.txt")
NAME: Joe Smith
CLASS: Fighter
STR: 14
DEX: 7
Here's what my program looks like:
player_name = None
player_class = None
player_STR = None
player_DEX = None
f = open("data.txt")
data = f.readlines()
for d in data:
# parse input, assign values to variables
print(d)
f.close()
My question is, how do I assign the values to the variables (something like setting player_STR = 14 within the program)?
player = {}
f = open("data.txt")
data = f.readlines()
for line in data:
# parse input, assign values to variables
key, value = line.split(":")
player[key.strip()] = value.strip()
f.close()
now the name of your player will be player['name'], and the same goes for all other properties in your file.
import re
pattern = re.compile(r'([\w]+): ([\w\s]+)')
f = open("data.txt")
v = dict(pattern.findall(f.read()))
player_name = v.get("name")
plater_class = v.get('class')
# ...
f.close()
The most direct way to do it is to assign the variables one at a time:
f = open("data.txt")
for line in f: # loop over the file directly
line = line.rstrip() # remove the trailing newline
if line.startswith('NAME: '):
player_name = line[6:]
elif line.startswith('CLASS: '):
player_class = line[7:]
elif line.startswith('STR: '):
player_strength = int(line[5:])
elif line.startswith('DEX: '):
player_dexterity = int(line[5:])
else:
raise ValueError('Unknown attribute: %r' % line)
f.close()
That said, most Python programmers would stored the values in a dictionary rather than in variables. The fields can be stripped (removing the line endings) and split with: characteristic, value = data.rstrip().split(':'). If the value should be a number instead of a string, convert it with float() or int().

Categories