Hangman code having trouble accessing other file - python

So I made a program for hangman that accesses an input file but it is having trouble accessing it once I type it in.
This is the function that is calling the file
def getWord(filename):
print("Loading from file...")
inputFile = open(filename, 'r')
wordlist = inputFile.read().splitlines()
print(len(wordlist) + " lines loaded.")
return wordlist
filename = input("What file will the words come from? ")
wordlist = getWord(filename)
theWordLine = random.choice(wordlist)
game(theWordLine)
And this is the file itself
person,Roger
place,Home
phrase,A Piece Of Cake
The error it is giving me is this
File "hangman.py' , line 77, in <module>
wordlist = getWord(filename)
File "hangman.py' , line 10, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Can anyone help me out?

The error states: TypeError: unsupported operand type(s) for +: 'int' and 'str'. That means that you cannot use + with something of type int and something of type str. the len function returns an int. Thus you need to cast it into a str before you being able to concatenate it with another str
It should be print(str(len(wordlist)) + " lines loaded.") instead of print(len(wordlist) + " lines loaded.")
You may also want to use string formatting as a comment mentions. If you are using python 3.6 or higher, you can try f-strings: f'{len(wordlist)} lines loaded}'.

It has nothing to do with reading the file. Read the error: an integer and string cannot be added.
Why are you getting this error? Because len() returns an integer, not a string. You can cast len()'s return to a string, or you can just use an f-string:
f'{len(wordlist)} lines loaded}'

Use print(len(wordlist), " lines loaded.") instead of print(len(wordlist) + " lines loaded.")

print(len(wordlist) + " lines loaded.") is causing your issue as it is trying to apply the + operand to variables of different datatypes.
You could use print("{} lines loaded".format(len(wordlist))) to avoid this.

Related

I want to have a word print alongside a textio that describes if the file is readable

The error it gives me is:
expected type 'str', got 'bool' instead"
code:
stuff = open("stuff.txt", "r")
print("File readable = " + stuff.readable())
print(stuff.readlines())
stuff.close()
You need to convert boolean to string:
print("File readable = " + str(stuff.readable()))
Or use f-strings or formatted string literals:
print(f"File readable = {stuff.readable()}")

'/' understood as a float?

I am looping through a pandas dataframe and trying to append the result on a conditional statement. However, my code seems to be posing a problem stopping me from append what I want although it prints fine but displays the error in the end. here is my code below:
counta=[]
for line in ipcm_perf['Alarms']:
if '/' in line:
print (line)
the error I get is the following :
2 for line in ipcm_perf['Alarms']:
----> 3 if ('/') in line:
4 print (line)
5
TypeError: argument of type 'float' is not iterable
I really do not know why Python is flagging that line. where's the float? Everything is being printed but with error at the bottom. It is stopping from appending.
your problem is that you are trying to check if there is a string (/) in a floating number (line), and Python does not like that.
That's because when you write "/" in some_string Python iterates through each char of some_string, but he can iterate through a floating number.
you can double check this by simply running:
if '/' in 3.14:
print("something")
output:
TypeError: argument of type 'float' is not iterable
I suppose that you're searching for a / because you've seen that somewhere in the column. If that's the case, it probably is in a string, and if that's the case, a quick&dirty way to clean your data can be:
if type(line) == str:
if "/" in line:
print(line)
else:
print("I am not a string")
and with line = 3.14, it returns:
I am not a string
and with line = "4/2", it returns:
I am a string

why is this type of variable not compatible with string?

I am trying to ask the user what they want to name a file that is about to be created on my desktop. When I try to add the variable to the string, it gives me this error:
appendFile = open('%s.txt', 'a') % cusername
TypeError: unsupported operand type(s) for %: '_io.TextIOWrapper' and 'str'
Here is my program:
def CNA():
cusername = input("Create username\n>>")
filehandler = open("C:/Users/CJ Peine/Desktop/%s.txt", "w") % cusername
filehandler.close()
cpassword = input("Create password\n>>")
appendFile = open('%s.txt', 'a') % cusername
appendFile.write(cpassword)
appendFile.close()
print ("Account Created")
How do I make the variable compatible to the string?
Try doing
cusername = input("Create username\n>>")
filehandler = open("C:/Users/CJ Peine/Desktop/" + cusername + ".txt", "w")
instead. Or you're just trying use modulus operator % on open function.
The % operator for formatting strings should take a string str as a first argument but instead you're passing the object returned from open(...). You can use this expression instead:
open("C:/Users/CJ Peine/Desktop/%s.txt" % cusername, "w")
Alternatively, Python 3 supports using the str.format(str) method ("C:/Users/CJ Peine/Desktop/{}.txt".format(cusername)), which IMHO is much more readable, and Python 3 is much better than Python 2 anyway. Python 2 has been out of active development for ages and is scheduled to no longer be supported; please don't use it unless you absolutely have to.

How to sum values for the same key [duplicate]

This question already has answers here:
I'm getting a TypeError. How do I fix it?
(2 answers)
Why dict.get(key) instead of dict[key]?
(14 answers)
Closed 6 months ago.
I have a file
gu|8
gt|5
gr|5
gp|1
uk|2
gr|20
gp|98
uk|1
me|2
support|6
And I want to have one number per TLD like:
gr|25
gp|99
uk|3
me|2
support|6
gu|8
gt|5
and here is my code:
f = open(file,'r')
d={}
for line in f:
line = line.strip('\n')
TLD,count = line.split('|')
d[TLD] = d.get(TLD)+count
print d
But I get this error:
d[TLD] = d.get(TLD)+count
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Can anybody help?
Taking a look at the full traceback:
Traceback (most recent call last):
File "mee.py", line 6, in <module>
d[TLD] = d.get(TLD) + count
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
The error is telling us that we tried to add something of type NoneType to something of type str, which isn't allowed in Python.
There's only one object of type NoneType, which, unsurprisingly, is None – so we know that we tried to add a string to None.
The two things we tried to add together in that line were d.get(TLD) and count, and looking at the documentation for dict.get(), we see that what it does is
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
Since we didn't supply a default, d.get(TLD) returned None when it didn't find TLD in the dictionary, and we got the error attempting to add count to it. So, let's supply a default of 0 and see what happens:
f = open('data','r')
d={}
for line in f:
line = line.strip('\n')
TLD, count = line.split('|')
d[TLD] = d.get(TLD, 0) + count
print d
$ python mee.py
Traceback (most recent call last):
File "mee.py", line 6, in <module>
d[TLD] = d.get(TLD, 0) + count
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Well, we've still got an error, but now the problem is that we're trying to add a string to an integer, which is also not allowed, because it would be ambiguous.
That's happening because line.split('|') returns a list of strings – so we need to explicitly convert count to an integer:
f = open('data','r')
d={}
for line in f:
line = line.strip('\n')
TLD, count = line.split('|')
d[TLD] = d.get(TLD, 0) + int(count)
print d
... and now it works:
$ python mee.py
{'me': 2, 'gu': 8, 'gt': 5, 'gr': 25, 'gp': 99, 'support': 6, 'uk': 3}
Turning that dictionary back into the file output you want is a separate issue (and not attempted by your code), so I'll leave you to work on that.
To answer the title of your question: "how to sum values for the same key" - well, there is the builtin class called collections.Counter that is a perfect match for you:
import collections
d = collections.Counter()
with open(file) as f:
tld, cnt = line.strip().split('|')
d[tld] += int(cnt)
then to write back:
with open(file, 'w') as f:
for tld, cnt in sorted(d.items()):
print >> f, "%s|%d" % (tld, cnt)

Concatenating strings then printing

print ("Tag Value " + i.tags.get('Name'))
gives me:
File "./boto_test.py", line 19, in main
print ("Tag Value" + i.tags.get('Name'))
TypeError: cannot concatenate 'str' and 'NoneType' objects
What is the correct way to do this?
Or just convert whatever you get from i.tags to string:
print ("Tag Value " + str(i.tags.get('Name')))
i.tags doesn’t contain a 'Name' key. What should the result be for None? Just pass it as a second argument to get:
print ("Tag Value " + i.tags.get('Name', 'None'))
Try converting it to the string data type by str() function.
Use the following code for the same line:
print ("Tag Value" + str(i.tags.get('Name')))

Categories

Resources