how to check integer and string in a list - python

My list is ['1','2','to','3']
I need to write a logic that
convert '1' '2' which is string to 1, 2 which is integer
print an error msg since 'to' string is included and cannot be converted to integer
Here's the code I have right now:
def average_file(filename):
inputFile = open(filename, "r")
inList = []
results = []
n = []
for line in inputFile:
inList.append(line.strip()) #inList.append(line)
n = [int(elem) for elem in inList if elem.isdigit()] #I only remove the string and leave integer in my list, but I need a check logic to print error msg
results = list(map(int, n))
inputFile.close()
results = sum(results)/len(results)
return results

Few things:
The pythonic way to do it is to expect it to be an all digit value and handle the error when it is not.
You can use with to handle your file lifetime.
You can calculate sum and count of elements during the reading without saving additional array (and therefore know the average).
strip is redundant when parsing to int like that int(variable):
There you go:
def average_file(filename):
summary = 0
count = 0
with open(filename, "r") as inputFile:
for line in inputFile:
try:
summary += int(line)
count += 1
except ValueError as e:
print('Can not parse "{0}" to a number'.format(line))
# If reached here one of the values in the file is not a number and None is returned immediately
return None
# If count is 0 return None, otherwise return the average
return (summary / count) if count else None
The answer was edited after some clarifications from OP:
Immediately return None when one of the values is not a number.

convert '1' '2' which is string to 1, 2 which is integer print an
error msg since 'to' string is included and cannot be converted to
integer
source = ['1', '2', 'to', '3']
result = []
for item in source:
try:
result.append(int(item))
except ValueError as ex:
print('Not integer: {}'.format(item))
print(result)

Attempt to convert each item to the list of results. If the conversion fails, print an error message.
l = ['1','2','to','3']
result = []
for item in l:
try:
result.append(int(item))
except ValueError:
print(item)

You can use a try/except block to separate the valid integer literals from everything else:
candidates = ['1','2','to','3']
for candidate in candidates:
try: # attempt the conversion
value = int(candidate)
except ValueError: # conversion failed!
print(candidate, 'is not an integer')
else: # conversion succeeded
print(candidate, 'is the integer', value)
In your case, you can just collect the values in the else clause:
results = []
with open(filename) as input_file:
for line in inputFile:
try:
value = int(line.strip())
except ValueError:
print(line.strip(), 'is not an integer')
else:
results.append(value)

l = ['1', '2', 'word', '4']
You can do:
n = [int(i) if i.isdigit() else print('\nNot able to convert: '+i) for i in l]
Output:
Not able to convert: word
l = [1, 2, None, 4]

Related

How to find specific index by its content

wordlist = open(r'C:\Users\islam\Desktop\10k most passwords.txt')
for words in wordlist:
line = (words.split())
for count, ele in enumerate(wordlist, 1):
x=(([count, ele]))
print(x)
The output :
[9994, 'hugohugo\n']
[9995, 'eighty\n']
[9996, 'epson\n']
[9997, 'evangeli\n']
[9998, 'eeeee1\n']
[9999, 'eyphed']
How could I find index 0 by typing its content , like input 9995 and the output be :
[9995, 'eighty\n']
This is one approach:
with open('path/to/file') as file:
data = file.readlines()
while True:
try:
user_input = int(input('Enter index:'))
if user_input < 1:
raise ValueError
print(data[user_input - 1].strip())
except (ValueError, IndexError):
print('Invalid index value')
I would say pretty simple since if You split by readlines it already is a list and can be accessed using indexes (subtract 1 to "start" index from 1), the rest of the code that includes error handling is for user convenience.
Simply for getting a value from a "hardcoded" index:
with open('path/to/file') as file:
data = file.readlines()
index = 5
print(data[index - 1])
you can try this:
list.index(element, start, end)
element - the element to be searched
start (optional) - start searching from this index
end (optional) - search the element up to this index
At the place of list you write your list name.
I think this may help

find the longest word and the largest number in a text file

So im learning python right now and i really need your help.
For example you do have random text file with words and numbers inside.
You need to find the longest word and maximum number in this file.
I managed to do the first half, i found the longest word:
def longest_word(word):
with open(word, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print (("the longest word is :"), longest_word ('text.txt'))
can you help me with the second part? how to find maximum number in a file?
You can implement error handling and try to parse the str as int: "2" --> 2
def longest_integer(word):
max_int = 0
with open(word, 'r') as infile:
words = infile.read().split()
for word in words:
try:
int_val = int(word)
if int_val > max_int:
max_int = int_val
except:
pass
return max_int
print (("the longest integer is :"), longest_integer ('text.txt'))
You're almost there! You can check each word to see if it's actually an integer, and then check if that value is greater than the previous max. This assumes the goal is to find the largest integer
for word in words:
try:
if int(word) > MAX_INT:
MAX_INT = word
except:
pass
with open(word, 'r') as infile:
data = infile.read()
nums = [int(num) for num in re.findall('\d+', data)
max_num = max(nums)
As numbers are integers you might get them using str's method isdigit, consider following example:
words = ['abc', '123', 'xyz', '1', '999']
numbers = [i for i in words if i.isdigit()]
print(numbers) # ['123', '1', '999']
then you might provide max with int as key following way:
print(max(numbers, key=int)) # 999
remember to NOT compare strs representing numbers as it might give surprising results, for example:
print(max(['9000','999'])) # 999
note that ValueError will occur if original list (words) do not contain any number.
Edit: I forget to note that above works solely for non-negative integers, to allow also negative one, you might write function for checking that as follow:
def represent_int(x):
if not x: # empty str
return False
if x[0] == '-': # leading - that is negative integer
return x[1:].isdigit()
return x.isdigit()
and use it as follows:
numbers = [i for i in words if represent_int(i)]
note that I assume represent_int will be feeded solely with strs.

Read only the numbers from a txt file python

I have a text file that contains these some words and a number written with a point in it. For example
hello!
54.123
Now I only want the number 54.123 to be extracted an converted so that the outcome is 54123
The code I tried is
import re
exp = re.compile(r'^[\+]?[0-9]')
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
if re.match(exp, line.strip()):
my_list.append(int(line.strip()))
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
But this returns the error: ValueError: invalid literal for int() with base 10: '54.123'
Does anyone know a solution for this?
You can try to convert the current line to a float. In case the line does not contain a legit float number it returns a ValueError exception that you can catch and just pass. If no exception is thrown just split the line at the dot, join the 2 parts, convert to int and add to the array.
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
try:
tmp = float(line)
num = int(''.join(line.split(".")))
my_list.append(num)
except ValueError:
pass
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
You can check if a given line is a string representing a number using the isdigit() function.
From what I can tell you need to just check if there is a number as isdigit() works on integers only (floats contain "." which isn't a number and it returns False).
For example:
def numCheck(string):
# Checks if the input string contains numbers
return any(i.isdigit() for i in string)
string = '54.123'
print(numCheck(string)) # True
string = 'hello'
print(numCheck(string)) # False
Note: if your data contains things like 123ab56 then this won't be good for you.
To convert 54.123 to 54123 you could use the replace(old, new) function.
For example:
string = 54.123
new_string = string.replace('.', '') # replace . with nothing
print(new_string) # 54123
This may help I am now getting numbers from the file I guess you were trying to use split in place of strip
import re
exp = re.compile(r'[0-9]')
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
for numbers in line.split():
if re.match(exp, numbers):
my_list.append(numbers)
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)

convert a string from a list to a float

I have a list with strings. Some of the strings contain alphabets and some contain numbers. I want to convert one of the strings with numbers in it to a float but getting an error
the list is called x. the 3rd element of the list is numbers. I tried x[2] = float (x[2]) but it gives me :Value error: could not convert string to a float:%"
See line 12 of the code where I am comparing float(x[2]) with 100
def file_read(fname):
i = 0
content_array = []
with open(fname, 'r') as f:
#Content_list is the list that contains the read lines.
for line in f:
content_array.append(line)
x = content_array[i].split('|')
i = i + 1
x[2] = x[2].strip() # to delete any empty spaces
if float(x[2]) > 50.00:
print ('got one')
print x[2]
print i
file_read('flow.txt')
Around your if statement you can wrap a try/except block, the program will try to convert float(x[2]) to a float, but if it cannot (since its a string) it will execute the except portion of the code.
try:
if float(x[2]) > 50.0:
print('got one')
except:
# do something else, if x[2] is not a float
pass # if you don't want to do anything.
You can use regular expressions to check if it's a number, and then you can safely cast it to float.
import re
rgx = "^\d*\.?\d*$"
if re.match(rgx, x):
print("it's a number!")
x = float(x)

Python: Adding numbers in a list

The question is to iterate through the list and calculate and return the sum of any numeric values in the list.
That's all I've written so far...
def main():
my_list = input("Enter a list: ")
total(my_list)
def total(my_list1):
list_sum = 0
try:
for number in my_list1:
list_sum += number
except ValueError:
#don't know what to do here
print list_sum
main()
If you check to see whether the list item is an int, you can use a generator:
>>> a = [1, 2, 3, 'a']
>>> sum(x for x in a if isinstance(x, int))
6
You can use a generator expression such that:
from numbers import Number
a = [1,2,3,'sss']
sum(x for x in a if isinstance(x,Number)) # 6
This will iterate over the list and check whether each element is int/float using isinstance()
Maybe try and catch numerical
this seams to work:
data = [1,2,3,4,5, "hfhf", 6, 4]
result= []
for d in data:
try:
if float(d):
result.append(d)
except:
pass
print sum(result) #25, it is equal to 1+2+3+4+5+6+4
Using the generator removes the need for the below line but as a side note, when you do something like this for this:
try:
for number in my_list1:
list_sum += number
except ValueError:
#don't know what to do here
You need to call float() on the number to force a ValueError when a string is evaluated. Also, something needs to follow your except which could simply be pass or a print statement. This way of doing it will only escape the current loop and not continue counting. As mentioned previously, using generators is the way to go if you just want to ignore the strings.
def main():
my_list = input("Enter a list: ")
total(my_list)
return
def total(my_list1):
list_sum = 0
try:
for number in my_list1:
list_sum += float(number)
except ValueError:
print "Error"
return list_sum
if __name__ == "__main__":
main()

Categories

Resources