如何将文本文件读取到独立列表中 Python
假设我有一个这样的文本文件:
100 20 the birds are flying
我想把里面的数字放到一个列表里,把字符串放到另一个列表里...我该怎么在Python中实现呢?我试过
data.append(map(int, line.split()))
但没有成功...有没有人能帮帮我?
4 个回答
2
这里有一个简单的解决方案。不过要注意,对于非常大的文件,这种方法可能没有其他方法高效,因为它会对每一行中的word
进行两次循环。
words = line.split()
intList = [int(x) for x in words if x.isdigit()]
strList = [x for x in words if not x.isdigit()]
3
如果我理解你的问题没错的话:
import re
def splitList(list):
ints = []
words = []
for item in list:
if re.match('^\d+$', item):
ints.append(int(item))
else:
words.append(item)
return ints, words
intList, wordList = splitList(line.split())
这段代码会给你两个列表:一个是 [100, 20]
,另一个是 ['the', 'birds', 'are', 'flying']
4
基本上,我是逐行读取文件,然后把每一行分开。我首先检查能不能把它们变成整数,如果不行,就把它们当作字符串来处理。
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']