0

我在数据文件中拆分文本时遇到问题,假设数据文件包括:

Row 1
apple
bob
cat
dog
ear
fun

Row 2
glow
horse
idea
joke
kick
lemon

Row 3
money
new
odd
park
queen
run

我想拆分它,使它成为一个嵌套列表,如下所示:

[[apple, bob], [cat, dog], [ear, fun]], 
[[glow, horse], [idea, joke], [kick, lemon]], 
[[money, new], [odd, park], [queen, run]]

这是我到目前为止的工作:

def text_file(data_file):
    nested_list = []
    main_list = []
    my_list = ''
    for index in data_file:
        index = index.strip()

        if (index in my_list):
            main_list.append(nested_list)
            nested_list = []

        else:
            nested_list.append(index)

    if (nested_list):
        main_list.append(nested_list)

    return (main_list)

但这会返回:

text_file(open("data_file.txt", "r"))
[['Row 1', 'apple', 'bob', 'cat', 'dog', 'ear', 'fun'], 
['Row 2', 'glow', 'horse', 'idea', 'joke', 'kick', 'lemon'], 
['Row 3', 'money', 'new', 'odd', 'park', 'queen', 'run']]

导入任何东西,我怎么能做到这一点?如果可能的话,我可以在我的代码中添加什么?

4

3 回答 3

5

您需要做的是按\n\n(两个换行符)拆分文件,这将为您提供组,然后按行拆分结果,然后使用zip适当地跨过文件以构建所需的列表,例如:

s = """Row 1
apple
bob
cat
dog
ear
fun

Row 2
glow
horse
idea
joke
kick
lemon

Row 3
money
new
odd
park
queen
run"""

lines = s.split('\n\n')
for line in lines:
    words = line.splitlines()
    print([ [i, j] for i, j in zip(words[1::2], words[2::2]) ])

[['apple', 'bob'], ['cat', 'dog'], ['ear', 'fun']]
[['glow', 'horse'], ['idea', 'joke'], ['kick', 'lemon']]
[['money', 'new'], ['odd', 'park'], ['queen', 'run']]
于 2012-11-30T07:59:57.907 回答
1

像这样,使用regexand iterators

使用regexsplit at Row number,然后您可以使用zipiterator来获得预期的输出。

In [8]: with open("data.txt") as f:
    spl=re.split(r"Row \d+",f.read())[1:]
    for x in spl:
        sp=x.split()
        it=iter(sp)
        print ([[next(it),next(it)] for _ in range(len(sp)//2)])
   ...:         
[['apple', 'bob'], ['cat', 'dog'], ['ear', 'fun']]
[['glow', 'horse'], ['idea', 'joke'], ['kick', 'lemon']]
[['money', 'new'], ['odd', 'park'], ['queen', 'run']]
于 2012-11-30T08:04:39.003 回答
0
if (nested_list):
    new_list = nested_list[1:]
    main_list.append(zip(new_list[::2], new_list[1::2]))

试试这个

上面的代码不是在主列表中附加嵌套列表,而是首先形成连续元素对,然后附加它。

于 2012-11-30T07:59:10.820 回答