Essentially, I'm reading the file line by line, and splitting them. I first check to see if I can turn them into an integer, and if I fail, treat them as strings.
def separate(filename):
all_integers = []
all_strings = []
with open(filename) as myfile:
for line in myfile:
for item in line.split(' '):
try:
# Try converting the item to an integer
value = int(item, 10)
all_integers.append(value)
except ValueError:
# if it fails, it's a string.
all_strings.append(item)
return all_integers, all_strings
Then, given the file ('mytext.txt')
100 20 the birds are flying
200 3 banana
hello 4
...doing the following on the command line returns...
>>> myints, mystrings = separate(r'myfile.txt')
>>> print myints
[100, 20, 200, 3, 4]
>>> print mystrings
['the', 'birds', 'are', 'flying', 'banana', 'hello']
map(int, line.split())appliesintto the entire line. What caused you to think this would separate numbers from words?