如何将文本文件读入单独的python列表
假设我有一个如下格式的文本文件: 鸟儿在飞翔 我想把int(s)读入它们自己的列表,把字符串读入它自己的列表……在python中我该怎么做呢。我试过了如何将文本文件读入单独的python列表,python,file-io,Python,File Io,假设我有一个如下格式的文本文件: 鸟儿在飞翔 我想把int(s)读入它们自己的列表,把字符串读入它自己的列表……在python中我该怎么做呢。我试过了 data.append(map(int, line.split())) 这不起作用…有帮助吗?pop从列表中删除元素并返回它: words = line.split() first = int(words.pop(0)) second = int(words.pop(0)) 当然,这是假设您的格式总是intword… 然后连接字符串的其余部分
data.append(map(int, line.split()))
这不起作用…有帮助吗?
pop
从列表中删除元素并返回它:
words = line.split()
first = int(words.pop(0))
second = int(words.pop(0))
当然,这是假设您的格式总是intword…
然后连接字符串的其余部分:
words = ' '.join(words)
在Python 3中,您甚至可以这样做:
first, second, *words = line.split()
这是相当整洁的。尽管您仍然需要将
第一个
和第二个
转换为int
。如果我正确理解您的问题:
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']
基本上,我是逐行读取文件,并将其拆分。我首先检查是否可以将它们转换为整数,如果失败,则将它们视为字符串
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')
…在命令行上执行以下操作将返回
>>> myints, mystrings = separate(r'myfile.txt')
>>> print myints
[100, 20, 200, 3, 4]
>>> print mystrings
['the', 'birds', 'are', 'flying', 'banana', 'hello']
这里有一个简单的解决方案。注意,对于非常大的文件,它可能不如其他文件那样有效,因为它对每一行的
重复word
两次
words=line.split()
intList=[int(x)表示x,如果x.isdigit()]
strList=[x表示x,如果不是x,则表示x.isdigit()]
您的答案是可以的。但是一个更通用的解决方案呢?情况是我们不知道字符串和整数在文件中的出现。如eghello 1 2检查
在这种情况下,您的解决方案不会work@RanRag是的。我在阅读了其他答案后编辑了这个假设,这个问题在这方面并不清楚。如果它总是采用这种格式,我认为Python3一行程序是最好的选择。当然,假设他使用的是Python 3。是的,在这种情况下,一行是最好的解决方案。map(int,line.split())
将int
应用于整行。是什么让你认为这会把数字和单词分开?+1。异常的这种用法是完美的。删除“我不高兴…”这句话。这很好。是的,我在某个地方读到,异常应该只用于异常行为,这里的情况并非如此。我删除了它。“异常应该只用于异常行为”在Python中不是非常正确。在某些语言中为True,但在Python中不是。
>>> myints, mystrings = separate(r'myfile.txt')
>>> print myints
[100, 20, 200, 3, 4]
>>> print mystrings
['the', 'birds', 'are', 'flying', 'banana', 'hello']