如何将文本文件读入单独的列表python [英] How to read a text file into separate lists python

查看:99
本文介绍了如何将文本文件读入单独的列表python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个格式如下的文本文件:

Say I have a text file formatted like this:

100 20只鸟在飞翔

100 20 the birds are flying

,我想将int读入自己的列表中,并将字符串读入其自己的列表中……我将如何在python中进行处理.我尝试过

and I wanted to read the int(s) into their own lists and the string into its own list...how would I go about this in python. I tried

data.append(map(int, line.split()))

那没用...有什么帮助吗?

that didn't work...any help?

推荐答案

基本上,我正在逐行读取文件并将其拆分.我首先检查是否可以将它们转换为整数,如果失败,请将其视为字符串.

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

然后,给定文件('mytext.txt')

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']

这篇关于如何将文本文件读入单独的列表python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆