Turn each word into a variable with python - python

I have a text which I need to delete the first two words and store the numbers into a variable.
I am trying to split the words and then create a loop to store each word in a variable.
My text is: "ABA BLLO 70000000 12-2022"
So I am trying to store the numbers, which can alternate depending on the data set and create a variable for each of them.
text = "ABA BLLO 70000000 12-2022"
a = text.strip().strip("")
for a in text:
print(a)
So I would have three variables:
number = 70000000
month = 12
year = 2022

You can use the split function to split the string on white-spaces and convert all the splitted strings into a list. Then you can slice the array to remove the first two elements and destructure the remaining array into variables.
text = "ABA BLLO 70000000 12-2022"
x,y = text.split()[2:]
print(x,y)
NOTE : This would work only if there's a fixed format for the input string.

If i get your point right, then try to check this code:
text = "ABA BLLO 70000000 12-2022"
counter = 0
word = []
number = []
for a in text.split(" "):
if counter <= 1:
word.append(a)
else:
number.append(a)
counter += 1
print(word)
print(number)
The output will be
['ABA', 'BLLO']
['70000000', '12-2022']

I don't know if I'm catching your drift but here's my answer:
new_text = text.split(" ")
for i in range(2, len(new_text)):
if i == 2:
number = new_text[i]
else:
month = new_text[i].split("-")[0]
year = new_text[i].split("-")[1]
print(f"Number: {number}\nMonth: {month}\nYear: {year}")

After using something like
tempSplit = text.split()
You're going to get a list class.
result = [s for s in tempSplit if s.isdigit()]
And with that you can get int objects but problem with this last fourth element is a Date object you have to use another function for that.
As #roganjosh suggested with the comment you should check other tutorials to find out about different functions. Like for this instance maybe you can try split function then learn how to get only numbers from a list.
To get dates
month = tempSplit[3].split("-")[0]
year = tempSplit[3].split("-")[1]

Related

Python - Split in one iteration

Why are functions often not available like this SPLIT in the final image?
How can I use split in this iteration?
soup = BeautifulSoup(teste, "html.parser")
Vagas = soup.find_all(title="Vaga disponível.")
temp=[]
for i in Vagas:
on_click = i.get('onclick')
temp.append(on_click)
achado2 = temp.split('\'')[1::6]
print(temp)
Here you defined temp as a list. It is actually already split into a list of elements, so .split() can not be applied on a list.
split() may be applied on a string to make from it a list of substrings.
Solved it by turning my list into a string and then using split on it again.
temp=[]
for i in Vagas:
on_click = i.get('onclick')
temp.append(on_click)
texto = str(temp)
achado2 = texto.split('\'')[1::6]

In what format does this variable need to be?

This is one of the programs I need to make on finals. The assignment is to write a name of racer and his three throws after that. For example: Adam 150 60 70. Then i need to find his max and min throw. I also need to write this data in txt file. I stripped this var of all text, only numbers remained. But I have problem with basic math functions. It takes e.g. number 150 as separate digits 1 5 0. I assume I have this variable in wrong format. I tried to convert it to almost everything, but nothing worked. I know this is silly problem, but if you know how to fix or rewrite this program I would appreciate it.
from fileinput import close
from string import ascii_letters
alp = ascii_letters
n = int(input('Number of racers: '))
subor = open('hod_ostepom_tx.txt','r+')
with open('hod_ostepom_tx.txt','r+') as f:
f.truncate(0)
for i in range (n):
name = input('Name of racer and his three throws: ')
subor.write(name + '\n')
for ele in alp:
name = name.replace(ele,'')
name = name.replace(' ','')
print('Maximum is: ',max(name))
print('Minimum is: ',min(name))
subor = close()
Name of racer and his three throws: Adam 150 60 70
Maximum is: 7
Minimum is: 0
In this case I would expect outcome of Maximum is : 150 Minimum is : 60
You can use a useful function str.split() to split the string by spaces, thus by doing this:
user_input = input('Name of racer and his three throws: ').split()
user_input will be ['Adam', '150', '60', '70']. You'll only need to get the name and convert string numbers to integer numbers. To remove first element form a list you can use .pop() function:
name = user_input.pop(0)
Now there's no 'Adam' in the list, only throws. To convert the ist of string to a list of numbers, you can use functional style:
throws = list(map(int, user_input))
name is a string. After you apply your replacements, name is still a string which contains only numbers. For your example name = "1506070". When you call max and min on a string it returns the character with the highest and lowest character code, 7 and 0 respectively. You can achieve what you want using the split function on the string. name_list = name.split(" ") will give a list name_list = ["Adam", "150", "60", "70"]. You can then use a list comprehension to convert the strings to integers:
name_list = name_list[1:] # Includes items at index 1 and after to get rid of name
name_list = [int(x) for x in name_list]
Then you can do max(name_list) or min(name_list) as the elements are integers and should give you what you want.

Should I Append or Join a list of dict and And how in python?

Using this code I was able to cycle through several instances of attributes and extract First and Last name if they matched the criteria. The results are a list of dict. How would i make all of these results which match the criteria, return as a full name each on it's own line as text?
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
print({players['firstName'], players['lastName']})
Results of Print Statement
{'Chandon', 'Sullivan'}
{'Urban', 'Brent'}
Are you looking for this:
print(players['firstName'], players['lastName'])
This would output:
Chandon Sullivan
Urban Brent
Your original trial just put the items to a set {}, and then printed the set, for no apparent reason.
Edit:
You can also for example join the firstName and lastName to be one string and then append the combos to a lists. Then you can do whatever you need with the list:
names = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
names.append(f"{players['firstName']} {players['lastName']}")
If you're using a version of Python lower than 3.6 and can't use f-strings you can do the last line for example like this:
names.append("{} {}").format(players['firstName'], players['lastName'])
Or if you prefer:
names.append(players['firstName'] + ' ' + players['lastName'])
Ok I figured out by appending the first and last name and creating a list for the found criteria. I then converted the list to a string to display it on the device.
full_list = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
full_list.append((players['firstName'] + " " + players['lastName']))
send_message('\n'.join(str(i) for i in full_list))

python add data to existing excel cell Win32com

Assume I have A1 as the only cell in a workbook, and it's blank.
I want my code to add "1" "2" and "3" to it so it says "1 2 3"
As of now I have:
NUMBERS = [1, 2, 3, 4, 5]
ThisSheet.Cells(1,1).Value = NUMBERS
this just writes the first value to the cell. I tried
ThisSheet.Cells(1,1).Value = Numbers[0-2]
but that just puts the LAST value in there. Is there a way for me to just add all of the data in there? This information will always be in String format, and I need to use Win32Com.
update:
I did
stringVar = ', '.join(str(v) for v in LIST)
UPDATE:this .join works perfectly for the NUMBERS list. Now I tried attributing it to another list that looks like this
LIST=[Description Good\nBad, Description Valid\nInvalid]
If I print LIST[0] The outcome is
Description Good
Bad
Which is what I want. But if I use .join on this one, it prints
('Description Good\nBad, Description Valid\nInvalid')
so for this one I need it to print as though I did LIST[0] and LIST[1]
So if you want to put each number in a different cell, you would do something like:
it = 1
for num in NUMBERS:
ThisSheet.Cells(1,it).Value = num
it += 1
Or if you want the first 3 numbers in the same cell:
ThisSheet.Cells(1,it).Value = ' '.join([str(num) for num in NUMBERS[:3]])
Or all of the elements in NUMBERS:
ThisSheet.Cells(1,1).Value = ' '.join([str(num) for num in NUMBERS])
EDIT
Based on your question edit, for string types containing \n and assuming every time you find a newline character, you want to jump to the next row:
# Split the LIST[0] by the \n character
splitted_lst0 = LIST[0].split('\n')
# Iterate through the LIST[0] splitted by newlines
it = 1
for line in splitted_lst0:
ThisSheet.Cells(1,it).Value = line
it += 1
If you want to do this for the whole LIST and not only for LIST[0], first merge it with the join method and split it just after it:
joined_list = (''.join(LIST)).split('\n')
And then, iterate through it the same way as we did before.

Sum in a mixed list of data

This is an specific questions that will help me finalize an outgoing project. It's pretty simple, I'm very new to Python and my background is mostly art. I like it, but I find it very challenging too.
I have a Text file (Data.txt) that contains a list of numbers/names, like this (short example):
String 1
34.6
45.6
45.9
String 2
34.6
45.6
45.9
This is a mixed list. After every String....12 numbers follow and so on. Notice that the numbers are 'float'.
I designed this:
numberList = []
data = []
data = open("SalesData.txt").read().split()
for i in data:
numberList.append(i)
print numberList
This will append and print all the data in the external .txt list. How can I get all that data in the new list (numberList), but excluding all the 'Strings' found through the reading of the file. This way, I can perform a total Sum of only the numbers ---
First, you shouldn't do .read().split() on your file - that will split on any whitespace, not just on newlines. Fortunately, Python can iterate directly over files.
Then, you could try to convert each line into a float and only append it to the list if that works (and skip it otherwise). Also, you can convert it to floats right away - makes summing it up easier.
number_list = []
with open("SalesData.txt") as myfile:
for line in myfile:
try:
number_list.append(float(line))
except ValueError:
pass
print(sum(number_list))
just iterate over the lines and only add the numbers to the list ...
with open("somefile.txt") as f:
my_list = []
for line in f:
try:
my_list.append(float(line))
except ValueError:
pass
print sum(my_list)
If your data is structured (which seems to be the case), I would simply use a counter and drop the 1st element of each sequence of len 12.
Here's an example:
numberList = []
data = []
counter = 0
with open("SalesData.txt") as myfile:
for line in myfile:
if counter > 0:
number_list.append(float(line))
counter = (counter + 1) % 12
print numberList
You could do type checking, or if the numbers are actually digits in a string, you could do something like a "13".isdigit() check but I'd probably want to do something a little more clever:
numberList = []
for i in range(0, len(data)/13):
numberList.append(data[1*(i+1):13*(i+1)])
That (or something like it) should target the groups of numbers after the strings. This does depend on your input data not being junk, but it should work quicker on large datasets than doing .isdigit() or other type checks.
try this:
tsum = []
for j in numberList:
try: tsum.append(float(j))
except: pass
sum = sum(tsum)
import re
ss = '''String 1
34.6
45.6
45.9
String 2
34.6
45.6
45.9
'''
print re.findall('^(?!.*?[a-zA-Z])[0-9.+-]+',ss,re.MULTILINE)
But if there can be letters whose none is ASCII, it won't work

Categories