基本上,我是逐行读取文件,然后将它们拆分。我首先检查是否可以将它们转换为整数,如果失败,则将它们视为字符串。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
然后,给定文件('mytext.txt')100 20 the birds are flying
200 3 banana
hello 4
…在命令行上执行以下操作返回。。。>>> myints, mystrings = separate(r'myfile.txt')
>>> print myints
[100, 20, 200, 3, 4]
>>> print mystrings
['the', 'birds', 'are', 'flying', 'banana', 'hello']