0

我想创建一个类来导入文本文件中的每个单独的行,如果可能的话将元素转换为 int,然后将这些对象附加到列表中。

另外,如果文本文件中的行超过 6 个单词,我想让前 2 个单词一起保存在列表中。

例如,我导入一个文本文件,如:

Hi my age is 15 16
If you want 13 to add
Please use 0 to add to it

用 3 个单独的对象制作一个列表,

[
    ['Hi', 'my', 'age' 'is', 15, 16], 
    ['If', 'you', 'want', 13, 'to', 'add'],
    ['Please use', 0, 'to', 'add', 'to', 'it',]
]

对python完全陌生,我希望能得到一些帮助,在此先感谢!

4

2 回答 2

2

This can be done very simply using a small loop construct. We can open the file as part of the loop and read line by line. Let's say you have a text file with what you entered above called 'foo.txt'.

myList = []
for line in open('foo.txt'):
    l.append(line.rstrip().split(' ')

This will create the list within list structure you're looking for. But wait, we're not done! Python parses values read this way as String types. As such, if the numbers are read in, they will actually be put into the list as a string, rather than the int you are looking to have. To determine if its a number, you can use the isdigit() method on string.

myList = []
for line in open('foo.txt'):
    temp = line.rstrip().split()
    toAdd = []
    for value in temp:
        if value.isdigit():
            toAdd.append( int(value) )
        else:
            toAdd.append(value)
    myList.append(toAdd)

This is by no means the best way to accomplish this problem, merely the first solution that came to mind. Odds are that entire loop can probably be performed as some sort of LC expression if one is willing to think on it.

It also doesn't fulfill your last requirement, but I do not think it would be tough to do. I encourage you to try improving on what I've provided. I highly recommend looking at what methods are available to you in the String and List classes in the Python documentation (http://docs.python.org/2/library/string.html and http://docs.python.org/2/library/stdtypes.html#typesseq respectively)

于 2013-11-13T14:58:34.613 回答
0
raw_data = open('textfile.txt', 'r')

lines = [ele.split() for ele in raw_data]

_list = []
_temp = []

for line in lines:
    for ele in line:
        try:
            _temp.append(int(ele.strip()))
        except:
            _temp.append(ele.strip())


    _list.append(_temp if (len(_temp) <= 6) else ["{0} {1}".format(_temp[0], _temp[1])]+_temp[2:])
    _temp = []

print _list

输出

[['Hi', 'my', 'age', 'is', 15, 16],
 ['If', 'you', 'want', 13, 'to', 'add'],
 ['Please use', 0, 'to', 'add', 'to', 'it']]
于 2013-11-13T15:02:12.370 回答