I am trying to figure out why my string won't concatenate - python

I am trying to print out the phrase variable to the terminal using multiple strings. I am trying to replace one string with another string.
I don't know what to try to make sure the code will concatenate.
firstName = "jason", "jennifer"
LastName = "Maraz", "Lopez"
actor = firstName[0], LastName[0]
actress = firstName[1], LastName[1]
introduceActor= "hi my name is ".join(actor)
print (actor, actress)
s = "lucky"
t = "happy", "greatful", "nice"
phrase = "I am so " + str(s) + " see " + actor + " today. I am as " + str(s) + " as could be"
phrase = phrase.replace(str(s), str(t[1]))
phrase2 = introduceActor
print(phrase)
print(phrase2)
index = phrase.find("i")
print(index)
the error I got was:
File "/Users/zachary/Documents/code proejcts/Test.py", line 11, in <module>
phrase = "I am so " + str(s) + " see " + actor + " today. I am as " + str(s) + " as could be"
TypeError: can only concatenate str (not "tuple") to str

Your "actor" and "actress" are tuples that hold 2 strings each.
For your purpose, you should probably use:
actor = firstName[0] + LastName[0]
actress = firstName[1] + LastName[1]
That way, you will have strings instead of tuples. Check here for more information

Related

How to divide numbers from a text file?

This is my file text:
Covid-19 Data
Country / Number of infections / Number of Death
USA 124.356 2.236
Netherlands 10.866 771
Georgia 90 NA
Germany 58.247 455
I created a function to calculate the ratio of deaths compared to the infections, however it does not work, because some of the values aren't floats.
f=open("myfile.txt","w+")
x="USA" + " " + " " + "124.356" + " " + " " + "2.236"
y="Netherlands" + " " + " " + "10.866" + " " + " " + "771"
z="Georgia" + " " + " " + "90" + " " + " " + "NA"
w="Germany" + " " + " " + "58.247" + " " + " " + "455"
f.write("Covid-19 Data" + "\n" + "Country" + " " + "/" + " " + "Number of infections" + " " + "/" + " " + "Number of Death" + "\n")
f.write(x + "\n")
f.write(y + "\n")
f.write(z + "\n")
f.write(w)
f.close()
with open("myfile.txt", "r") as file:
try:
for i in file:
t = i.split()
result=float(t[-1])/float(t[-2])
print(results)
except:
print("fail")
file.close()
Does someone have an idea how to solve this problem ?
You can do the following:
with open("myfile.txt", "r") as file:
for i in file:
t = i.split()
try:
result = float(t[-1]) / float(t[-2])
print(result)
except ValueError:
pass
At the time you don't know if the values you are trying to divide are numeric values or not, therefore surrounding the operation with a try-catch should solve your problem.
If you want to become a bit more "clean" you can do the following:
def is_float(value):
try:
float(value)
except ValueError:
return False
return True
with open("myfile.txt", "r") as file:
for i in file:
t = i.split()
if is_float(t[-1]) and is_float(t[-2]):
result = float(t[-1]) / float(t[-2])
print(result)
The idea is the same, however.
I used the same file that you attached in your example. I created this function hopefully it helps:
with open("test.txt","r") as reader:
lines = reader.readlines()
for line in lines[2:]:
line = line.replace(".","") # Remove points to have the full value
country, number_infections, number_deaths = line.strip().split()
try:
number_infections = float(number_infections)
number_deaths = float(number_deaths)
except Exception as e:
print(f"[WARNING] Could not convert Number of Infections {number_infections} or Number of Deaths {number_deaths} to float for Country: {country}\n")
continue
ratio = number_deaths/number_infections
print(f"Country: {country} D/I ratio: {ratio}")
As you can see I avoided the headers of your file using lines[2:] that means that I will start from row 3 of your file. Also, added try/exception logic to avoid non-float converts. Hope this helps!
Edit
Just noticed that the format for thousands is used with "." instead "," in that case the period was removed in line 7.
The results for this execution is:
Country: USA D/I ratio: 0.017980636237897647
Country: Netherlands D/I ratio: 0.07095527332965212
[WARNING] Could not convert Number of Infections 90.0 or Number of Deaths NA to float for Country: Georgia
Country: Germany D/I ratio: 0.007811561110443456
Fixed the following:
The first two lines in your text-file are headers. These need to be skipped
'NA' Can't be converted to zero
If there is a 0 in your data, your program would crash. Now it wouldn't.
f=open("myfile.txt","w+")
x="USA" + " " + " " + "124.356" + " " + " " + "2.236"
y="Netherlands" + " " + " " + "10.866" + " " + " " + "771"
z="Georgia" + " " + " " + "90" + " " + " " + "NA"
w="Germany" + " " + " " + "58.247" + " " + " " + "455"
f.write("Covid-19 Data" + "\n" + "Country" + " " + "/" + " " + "Number of infections" + " " + "/" + " " + "Number of Death" + "\n")
f.write(x + "\n")
f.write(y + "\n")
f.write(z + "\n")
f.write(w)
f.close()
with open("myfile.txt", "r") as file:
#Skipping headers
next(file)
next(file)
try:
for i in file:
t = i.split()
#Make sure your code keeps working when one of the numbers is zero
x = 0
y = 0
#There are some NA's in your file. Strings not representing
#a number can't be converted to float
if t[1] != "NA":
x = t[1]
if t[2] != "NA":
y = t[2]
if x == 0 or y == 0:
result = 0
else:
result=float(x)/float(y)
print(t[0] + ": " + str(result))
except:
print("fail")
file.close()
Output:
USA: 55.615384615384606
Netherlands: 0.014093385214007782
Georgia: 0
Germany: 0.12801538461538461
Your header line in the file is Covid-19 Data. this is the first line and when you call t=i.split() you then have a list t which has data ['Covid-19', 'Data']
you cannot convert these to floats since they have letters in them. Instead you should read the first 2 header line before the loop and do nothing with them. However you are then going to have issues with Georgia as "NA" also cannot be converted to a float.
A few other points, its not good practice to have a catch all exception. Also you dont need to close the file explicitly if you open the file using a with statement.

how to find out how many lines are in a variable

I'm doing a Telegram bot and I want to print string in Inline keyboard. I have a variable text which can change and I want to chack how much lines(string) in variable as it can do with it 0<name<2 and do restrictions. How can do it?
I could make it with len(), but it show me list index out range
text="head,hand,..."
selectKeyboard = telebot.types.InlineKeyboardMarkup( row_width=1)
if 0<name<2:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name']),callback_data="first")
selectKeyboard.add(one)
if 0<name<3:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" ",callback_data="first")
two=types.InlineKeyboardButton(text=str(text[1]['name'])+" ",callback_data="second")
selectKeyboard.add(one,two)
if 0<name<4:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" ",callback_data="first")
two=types.InlineKeyboardButton(text=str(text[1]['name'])+" ",callback_data="second")
three = types.InlineKeyboardButton(text=str(text[2]['name']) + " " ,callback_data="three")
selectKeyboard.add(one,two,three)
if 0<name<5:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" ",callback_data="first")
two=types.InlineKeyboardButton(text=str(text[1]['name'])+" "+,callback_data="second")
three = types.InlineKeyboardButton(text=str(text[2]['name']) + " " ,callback_data="three")
four = types.InlineKeyboardButton(text=str(text[3]['name']) + " " , callback_data="four")
selectKeyboard.add(one,two,three,four)
if 0<name<6:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" ",callback_data="first")
two=types.InlineKeyboardButton(text=str(text[1]['name'])+" ",callback_data="second")
three = types.InlineKeyboardButton(
text=str(text[2]['name']) + " " ,
callback_data="three")
four = types.InlineKeyboardButton(
text=str(text[3]['name']) + " " ,
callback_data="four")
five=types.InlineKeyboardButton(
text=str(text[4]['name']) + " " ,
callback_data="five")
selectKeyboard.add(one, two, three, four,five)
The following piece of code is not doing what you imagine, in fact it'll just return False, because name is a string and you're comparing it against integers:
0 < name < 2
Instead, you should test for the number of variables, like this:
text = "head,hand,..."
num_vars = len(text.split(','))
if 0 < num_vars < 2:
# same for all the other comparisons

Python 3: read file of names, create new file with first names and last names reverse

I am a noob to python and am stuck on a simple task. I looked at similar questions on stackoverflow but was not able to apply to my own problem. I have created a file with a list of names. How do I create a new file where it reads the original file (pretending that I don't know how many names are in the file) and reverses the names (people are in same order but with last name before first name). Below is my script:
firstname1 = "Morty"
lastname1 = "Smith"
fullname1 = firstname1 + " " + lastname1
firstname2 = "Donna"
lastname2 = "Gueterman"
fullname2 = firstname2 + " " + lastname2
firstname3 = "Beth"
lastname3 = "Smith"
fullname3 = firstname3 + " " + lastname3
firstname4 = "Rick"
lastname4 = "Sanchez"
fullname4 = firstname4 + " " + lastname4
firstname5 = "Little"
lastname5 = "Dipper"
fullname5 = firstname5 + " " + lastname5
formal_names = fullname1,fullname2,fullname3,fullname4,fullname5
f = open("names_normal.txt","w")
f.write("%s " % (formal_names, ))
f.close()
def reverse_list(lst):
new = []
count = len(lst)-1
while count >=0:
new.append(lst[count])
count -= 1
return new
x = reverse_list(formal_names)
n = open("names_new.txt","w")
n.write("%s " % (x, ))
n.close()
These are my results:
1st file:
('Morty Smith', 'Donna Gueterman', 'Beth Smith', 'Rick Sanchez',
'Little Dipper')
2nd file: ('Little Dipper', 'Rick Sanchez', 'Beth Smith', 'Donna Gueterman', 'Morty Smith')
What I want: ('Smith Morty', 'Gueterman Donna', 'Smith Beth', 'Sanchez Rick', 'Dipper Little')
Any help would be appreciated! Thank you so much!
def reverse_list(lst):
new = []
for name in lst:
temp = name.split(" ")
new += [temp[1]+" "+temp[0]]
You're just changing order of words in the array, you should change order of the name and surname with splitting from space.
def reverse_name(name):
# Try to fill here and update if doesn't work
def reverse_list(lst):
new = []
for name in lst:
new.append(reverse_name(name))
return new
This is how I attacked this problem. It's probably best to put this in a function as mentioned above.
firstname1 = "Morty"
lastname1 = "Smith"
fullname1 = firstname1 + " " + lastname1
firstname2 = "Donna"
lastname2 = "Gueterman"
fullname2 = firstname2 + " " + lastname2
firstname3 = "Beth"
lastname3 = "Smith"
fullname3 = firstname3 + " " + lastname3
firstname4 = "Rick"
lastname4 = "Sanchez"
fullname4 = firstname4 + " " + lastname4
firstname5 = "Little"
lastname5 = "Dipper"
fullname5 = firstname5 + " " + lastname5
formal_names = [fullname1,fullname2,fullname3,fullname4,fullname5]
reversed = []
for i in range(0, (len(formal_names))):
rev = formal_names[i].split()
rev_name = rev[1] + ' ' + rev[0]
reversed.append(rev_name)
print(reversed)
['Smith Morty', 'Gueterman Donna', 'Smith Beth', 'Sanchez Rick', 'Dipper Little']
now you just write the list to a file
with open('output.txt', 'w') as file:
for name in reversed:
file.write(name)
You are complicating matters using separate variables for each person's name. In Python the better way of handling this is to use one of python's data structures, in this case a list with each name contained in a tuple. The advantage of doing this is that you can iterate over the list and refer to parts of the name by position, for example: names[0][1] for "Smith".
names = [("Morty","Smith"),
("Donna","Gueterman"),
("Beth","Smith"),
("Rick","Sanchez"),
("Little","Dipper")]
Or, if you wish you can used a namedtuple to make things clear, especially if you add other data items for each person.
import collections
Person = collections.namedtuple('Person', 'first last')
names = [Person("Morty","Smith"),
Person("Donna","Gueterman"),
Person("Beth","Smith"),
Person("Rick","Sanchez"),
Person("Little","Dipper")]
The output can then be created with a list comprehension :
normal = ", ".join([name.first + " " + name.last for name in names])
reversed = "; ".join([name.last + ", " + name.first for name in names])
print(normal)
print(reversed)
You can alter the punctuation : the first string ", " is between names, the second string " " is between words. Then, use the method suggested in earlier answers to store the strings in a file.
(I would advise using punctuation between last and first otherwise you can run into problems with names like "Alan Simon".)

Python - Printing Reverse Name Order

If my list in a text file has the following
I want it to print out like
However my current code prints it out like
My code is:
def addStudent(student):
reg,year,degree,*name= student.strip().split(" ")
name = list(reversed(name))
fullName = name[0] + ", " + " ".join(name[1:])
return (reg,year,degree,name,fullName)
def employee(employee):
reg,year,degree,*name,fullName = employe
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))
How do i switch the order of the last two parts of the name? In which area is my code wrong because i'm not sure how else to reverse it. If i do add a print statement after the reversed function it does seperate each part of the name as a string, but when it joins, it does it in the wrong order
Just don't reverse the list:
def addStudent(student):
reg,year,degree,*name= student.strip().split()
fullName = "%s, %s" % (name[-1], " ".join(name[:-1]))
return (reg, year, degree, name, fullName)
Or change that line
fullName = name[0] + ", " + " ".join(name[1:])
to this
fullName = name[0] + ", " + " ".join(name[-1:0:-1])
Edit:
dat = '1234567 1 C100 Bartholomew Homer Simpson'
def addStudent(student):
reg,year,degree,*name= student.strip().split(" ")
name = list(reversed(name))
# You have now::
# name = ['Simpson', 'Homer', 'Bartholomew']
# Therefore , name[-1:0:-1]
# will select from last item in list 'Bartholomew to
# the 0th one, the 0th being excluded in reverse
fullName = name[0] + ", " + " ".join(name[-1:0:-1])
return (reg,year,degree,name,fullName)
def printStud(studentTuple):
reg,year,degree,*name,fullName = studentTuple
reg = int(reg)
thisYear = "Year "+str(year)
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))
Output :
In [1]:
Simpson, Bartholomew Homer 1234567 C100 Year 1
If you need sorted names, you can sort them using sorted()
a=["metallica", "therion", "acdc"]
print a[0],", "+" ".join( sorted(a[1:]))
out:
metallica , acdc therion

dict to list, and compare lists python

I have made a function, were I count how many times each word is used in a file, that will say the word frequency. Right now the function can calculate the sum of all words, and show me the seven most common words and how many times they are used. Now I want to compare my first file were I have analyzed the word frequency with another file were I have the most common words used in the english language, and I want to compare those words with the words I have in my first file to see if any of the words matches.
What I have come up to is to make lists of the two files and then compare them with each other. But the code I wrote for this doesn't give me any output, any idea on how I can solve this?
def CountWords():
filename = input('What is the name of the textfile you want to open?: ')
if filename == "alice" or "alice-ch1.txt" or " ":
file = open("alice-ch1.txt","r")
print('You want to open alice-ch1.txt')
wordcount = {}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
wordcount = {k.lower(): v for k, v in wordcount.items() }
print (wordcount)
sum = 0
for val in wordcount.values():
sum += val
print ('The total amount of words in Alice adventures in wonderland: ' + str(sum))
sortList = sorted(wordcount.values(), reverse = True)
most_freq_7 = sortList[0:7]
#print (most_freq_7)
print ('Totoro says: The 7 most common words in Alice Adventures in Wonderland:')
print(list(wordcount.keys())[list(wordcount.values()).index(most_freq_7[0])] + " " + str(most_freq_7[0]))
print(list(wordcount.keys())[list(wordcount.values()).index(most_freq_7[1])] + " " + str(most_freq_7[1]))
print(list(wordcount.keys())[list(wordcount.values()).index(most_freq_7[2])] + " " + str(most_freq_7[2]))
print(list(wordcount.keys())[list(wordcount.values()).index(most_freq_7[3])] + " " + str(most_freq_7[3]))
print(list(wordcount.keys())[list(wordcount.values()).index(most_freq_7[4])] + " " + str(most_freq_7[4]))
print(list(wordcount.keys())[list(wordcount.values()).index(most_freq_7[5])] + " " + str(most_freq_7[5]))
print(list(wordcount.keys())[list(wordcount.values()).index(most_freq_7[6])] + " " + str(most_freq_7[6]))
file_common = open("common-words.txt", "r")
commonwords = []
contents = file_common.readlines()
for i in range(len(contents)):
commonwords.append(contents[i].strip('\n'))
print(commonwords)
#From here's the code were I need to find out how to compare the lists:
alice_keys = wordcount.keys()
result = set(filter(set(alice_keys).__contains__, commonwords))
newlist = list()
for elm in alice_keys:
if elm not in result:
newlist.append(elm)
print('Here are the similar words: ' + str(newlist)) #Why doesn't show?
else:
print ('I am sorry, that filename does not exist. Please try again.')
I'm not in front of an interpreter so my code might be slightly off. But try something more like this.
from collections import Counter
with open("some_file_with_words") as f_file
counter = Counter(f_file.read())
top_seven = counter.most_common(7)
with open("commonwords") as f_common:
common_words = f_common.read().split()
for word, count in top_seven:
if word in common_words:
print "your word " + word + " is in the most common words! It appeared " + str(count) + " times!"

Categories

Resources