I'm writing a python script that reads a players name and stats from a sentence in a .txt file, then updates their stats within a dictionary and then prints out their average stats. I'm having trouble with assigning multiple values to the same 'player' key, as well as getting the logic below it to correctly update the player stats. The .group part is giving me trouble too. How can I do this?
import re, sys, os, math
if len(sys.argv) < 2:
sys.exit("Usage: %s filename" % sys.argv[0])
filename = sys.argv[1]
if not os.path.exists(filename):
sys.exit("Error: File '%s' not found" % sys.argv[1])
line_regex = re.compile(r"^(\w+ \w+) batted (\d+) times with (\d+) hits and (\d+) runs")
line = [line.strip() for line in open(filename)]
f = open (filename)
playerStats = {'players': [0, 0, 0]}
for players in playerStats:
player = line.group(1)
atBat = line.group(2)
hit = line.group(3)
if player in playerStats:
playerStats[player][0] += atBat
playerStats[player][1] += hit
if player not in players:
player = line.group(1)
playerStats[player][0] = atBat
playerStats[player][1] = hit
avgs = 0
else:
playerStats[player][0] = player
playerStats[player][0] = atBat
playerStats[player][1] = hit
playerStats[player][2] = 0
for player in players:
avgs[player] = round(float(hits[player])/float(atBats[player]), 3)
print "%s: %.3f" % (player, avgs[player])
Traceback (most recent call last):
File "ba.py", line 19, in
player = line.group(1)
AttributeError: 'list' object has no attribute 'group'
You should change this
playerStats = {'players': hits, atBats, avgs}
To
playerStats = {'players': [0, 0, 0]}
The latter stores the value as a list , the former is not valid Python syntax.
To modify one of these values you would do, for example
playerStats[player][1] = 5 # atBat value
You could also change to a nested structure like
playerStats = {'players': {'hits' : 0,
'atBats' : 0,
'avgs' : 0)}
Then you could modify the values as
playerStats[player]['hits'] = 3
Related
Im a beginner on Python, got an exercise on a youtube class that im having problem with, here is the code:
from datetime import date
list = []
data = {}
while True:
data['name'] = input('Name: ').title().strip()
data['birth'] = int(input('Year of birth [XXXX]: '))
data['age'] = date.today().year - data['birth']
data['ctps'] = int(input('Num. CPTS (if none enter 0): '))
if data['ctps'] != 0:
data['hiredate'] = int(input('Hired on: '))
data['income'] = float(input('What`s your income: $'))
data['retirement'] = (data['hiredate'] + 35) - data['birth']
list.append(data.copy())
data.clear()
p = input('Want to finish? [Y/N] ').upper().strip()
if p not in 'NY':
p = input('Invalid option. Want to finish? [Y/N]')
if p == 'Y':
break
print('-'*30)
for i in list:
print(f'Name is {data["name"]}')
and i get the following error:
Traceback (most recent call last):
File "C:\*****\******\*****\*****\*****.py", line 22, in <module>
print(f'Name is {data["name"]}')
KeyError: 'name'
I intent to run a for command through that list, printing each name added to the dictionary in that list. I know there are other ways of solving this (i usually use 'for i in range(0, len(list))'), but i wish to solve it this way, if possible.
Thank you in advance
I am working on a program to count anglicisms in German texts and everything works fine except when trying to output the results to a text file (at the bottom of the code). Here's my code so far:
from collections import Counter
import os.path
print('='*50)
print('Welcome to the ANGLICISM COUNTER 5000')
while True:
print('='*50)
lines, blanklines, sentences, words, setnum = 0,0,0,0,1
setname = input('Please enter setname: ')
listOfAnglicisms = open('anglicisms.txt').read().split()
listOfGermanWords = open('haufigste.txt').read().split()
anglicisms = []
falsepositive = []
def derivatesFromAnglicism(word):
return any([word.startswith(a) for a in listOfAnglicisms])
while os.path.isfile(str(setname+str(setnum)+".txt")) == True:
textf = open(setname+str(setnum)+'.txt')
for line in textf:
line = line.lower()
lines+=1
if line.startswith('\n'):
blanklines+=1
else:
sentences += line.count('.') + line.count('!') + line.count('?')
words += len(line.split(None))
anglicisms.extend([word for word in line.split() if derivatesFromAnglicism(word)])
anglicisms = [x for x in anglicisms if x not in listOfGermanWords]
setnum+=1
textf.close()
print('='*50)
print('Lines : ',lines)
print('Blanklines : ',blanklines)
print('Sentences : ',sentences)
print('Words: : ',words)
print('Anglicisms : ',len(anglicisms))
print('Words until anglicism : ',int(words)/len(anglicisms)-1)
print('All anglicisms :\n',Counter(anglicisms))
print('='*50)
while falsepositive != 'n':
falsepositive = input('Please enter a false positive or "n" to continue: ')
if falsepositive == 'n':
pass
else:
while falsepositive in anglicisms:
anglicisms.remove(falsepositive)
print('='*50)
print('Lines : ',lines)
print('Blanklines : ',blanklines)
print('Sentences : ',sentences)
print('Words: : ',words)
print('Anglicisms : ',len(anglicisms))
print('Words until anglicism : ',int(words)/len(anglicisms)-1)
print('All anglicisms :\n',Counter(anglicisms))
print('='*50)
results = open(setname+'.txt', 'w')
results.write(
('='*50)+
'\n'+
setname+'\n'+
'Lines : '+lines+'\n'+
'Blanklines : '+blanklines+'\n'+
'Sentences : '+sentences+'\n'+
'Words: : '+words+'\n'+
'Anglicisms : '+len(anglicisms)+'\n'+
'Words until anglicism : '+int(words)/len(anglicisms)-1+'\n'+
'All anglicisms :\n'+Counter(anglicisms)+'\n'+
('='*50)+
'\n'
)
results.close()
And this is the error I get:
Traceback (most recent call last):
File "C:\...\anglicism_counter_5000.py", line 81, in <module>
('='*50)+
TypeError: Can't convert 'int' object to str implicitly
I have tried using str() on the variables but it didn't help. Does anybody know how to use write() properly, so this error won't occur again?
The error message is a little confusing. It's quoting the line ('='*50), but the program actually crashes at
'Lines : '+lines+'\n'+
(I didn't count the lines, though.)
lines is an integer. SO you'd need to wrap it with str(...). Same for the other integers you're printing.
I'm trying to tally the number of instances of a top level domain occur in a file containing 800K+ top level domain strings that I scraped from URLs. In the code below, when I used "if mstlds in ntld:" the results appeared to be correct but upon inspection "co" and "com", "ca" and "cat" counts are incorrect. But if I use == or "is" I don't get any matches at all but instead an error:
Traceback (most recent call last):
File "checktlds4malware.py", line 111, in
mtlds_line = mtlds.readline()
AttributeError: 'str' object has no attribute 'readline'
tld_file = open(sys.argv[1],'r')
tld_line = tld_file.readline()
while tld_line:
#print(tld_line)
tld_line = tld_line.strip()
columns = tld_line.split()
ntld = columns[0] # get the ICANN TLD
ntld = ntld.lower()
mtlds = open ('malwaretlds.txt', 'r')
mtlds_line = mtlds.readline()
while mtlds_line:
print(mtlds_line)
mtlds_line = mtlds_line.strip()
columns = mtlds_line.split()
mtlds = columns[0]
mtlds = mtlds.lower()
#raw_input()
# I don't get the error when using "in" not ==
# but the comparison is not correct.
if mtlds_line == ntld:
m_count += 1
print 'ntld and mtld match: Malware domain count for ', ntld, m_count
mtlds_line = mtlds.readline()
print 'Final malware domain count for ', ntld, m_count
This is because within your while loop, you are setting mtlds to be a String. Thus, once you attempt to use the readline() method you throw the error (pretty self explanatory). You have to remember that only outside the scope of your interior while loop is mtlds pointing to a file.
So I am learning python and redoing some old projects. This project involves taking in a dictionary and a message to be translated from the command line, and translating the message. (For example: "btw, hello how r u" would be translated to "by the way, hello how are you".
We are using a scanner supplied by the professor to read in tokens and strings. If necessary I can post it here too. Heres my error:
Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
File "translate.py", line 26, in <module>
main()
File "translate.py", line 13, in main
dictionary,count = makeDictionary(commandDict)
File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
string = s.readstring()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
return self._getString()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)
Heres my main translate.py file:
from support import *
from scanner import *
import sys
def main():
arguments = len(sys.argv)
if arguments != 3:
print'Need two arguments!\n'
exit(1)
commandDict = sys.argv[1]
commandMessage = sys.argv[2]
dictionary,count = makeDictionary(commandDict)
message,messageCount = makeMessage(commandMessage)
print(dictionary)
print(message)
i = 0
while count < messageCount:
translation = translate(message[i],dictionary,messageCount)
print(translation)
count = count + 1
i = i +1
main()
And here is my support.py file I am using...
from scanner import *
def makeDictionary(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst = []
token = s.readtoken()
count = 0
while (token != ""):
lyst.append(token)
string = s.readstring()
count = count+1
lyst.append(string)
token = s.readtoken()
return lyst,count
def translate(word,dictionary,count):
i = 0
while i != count:
if word == dictionary[i]:
return dictionary[i+1]
i = i+1
else:
return word
i = i+1
return 0
def makeMessage(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst2 = []
string = s.readtoken()
count = 0
while (string != ""):
lyst2.append(string)
string = s.readtoken()
count = count + 1
return lyst2,count
Does anyone know whats going on here? I've looked through several times and i dont know why readString is throwing this error... Its probably something stupid i missed
chr(0x2018) will work if you use Python 3.
You have code that's written for Python 3 but you run it with Python 2. In Python 2 chr will give you a one character string in the ASCII range. This is an 8-bit string, so the maximum parameter value for chris 255. In Python 3 you'll get a unicode character and unicode code points can go up to much higher values.
The issue is that the character you're converting using chr isn't within the range accepted (range(256)). The value 0x2018 in decimal is 8216.
Check out unichr, and also see chr.
So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '¢er=' + common_finder(latit,longi)
else:
center = '¢er=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.