文件解析python recursi

2024-06-16 11:34:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学Python。你知道吗

我有这样的档案

str1 str2 str3 str4
str1 str2 str7 str8
***
str9 str10 str12 str13
str9 str10 str16 str17
****
str 18 str19 str20 str21 
***

等等。你知道吗

我想将其更改为此格式->

str1
str2 str3 str4
str2 str7 str8

str9
str10 str12 str13
str10 str16 str17

str 18
str19 str20 str21 

因此,如果前两个单词在两行之间是公共的,那么将两行排列在一起,并将第一个单词移到另一行。 这应该可以递归地改变,但我似乎不明白


Tags: strstr1str2str3str4str8str16str9
2条回答

使用OrderedDict存储最后三个字符串作为值,第一个字符串作为键,然后在末尾写入键和值。你知道吗

from collections import OrderedDict

od = OrderedDict()

with open("words.txt") as f,open("fixed.txt","w") as out:
    for line in f:
        if not line.startswith("*"):
            spl = line.split(None,1)
            od.setdefault(spl[0],[])
            od[spl[0]].append(spl[1:])
    for k, v in od.items():
        out.write("{}\n{}\n".format(k,"".join(" ".join(row) for row in v)))

稍微修改一下https://stackoverflow.com/a/28759802。。。你知道吗

from itertools import groupby

with open('input') as fin, open('output', 'w') as fout:
    stripped_lines = (line.rstrip('*\n') for line in fin)
    split_lines = (line.split(None, 1) for line in stripped_lines if line)
    for k, g in groupby(split_lines, lambda L: L[0]):
        fout.write('{}\n{}\n\n'.format(k, '\n'.join(el[1] for el in g)))

相关问题 更多 >