Python解析多列文件

时间:2016-08-17 17:49:49

标签: python parsing multiline

我有一个文件,我需要使用python解析并从多行构造到一行

docker-compose up -d --no-deps ServiceName

正如您在此处所见,文件头是NAME,ID,TITLE,DEP

我想打印输出如下所示我可以在csv文件中轻松阅读并轻松完成其他工作。

NAME ID

TITLE DEP

USER1  0023

S1  SALES

USER2  0022

A2  ACCOUNT

以下是我开始使用但无法到达我想要的地方的代码。 我尝试了不同的选项来拆分和替换,但没有奏效。

NAME, ID, TITLE, DEP
USER1,0023,S1,SALES
USER2,0022,A2,ACCOUNT

感谢任何帮助

3 个答案:

答案 0 :(得分:0)

在这里名为file.txt的文件中包含所有单词是代码:


# read all the words
with open('file.txt') as f:
    words = f.read().split()

# convert to groups of 4-s
groups4 = [words[i:i+4] for i in range(0, len(words), 4)]

# convert to lines with commas using join()
lines = [', '.join(lst) for lst in groups4]

# and here is the result
for line in lines:
    print(line)

输出:

NAME, ID, TITLE, DEP
USER1, 0023, S1, SALES
USER2, 0022, A2, ACCOUNT

答案 1 :(得分:0)

infile = open('test_file_parse.csv','r')
def custom_func(x):
    return next(x).strip().split()
while infile:
    try:
       print ','.join(reduce(lambda x, y: x + y, (custom_func(infile) for z in range(4))))
    except TypeError:
       break
infile.close()

答案 2 :(得分:0)

如果您知道所有内容都是成对的两行,并且您知道可以忽略空行,则可以执行以下操作:

infile = open('test_file_parse.csv', 'r')

# A generator that yields the non-empty lines, without newlines.
lines = (l.strip() for l in infile if l.strip())

# An iterator to iterate over the yielded lines.
line_iter = iter(lines)

# A generator to yield space-separated combined lines.
new_lines = (' '.join(l_pair) for l_pair in zip(line_iter, line_iter))

# Lastly, a generator to yield proper csv for the lines.
csv_lines = (','.join(l.split()) for l in new_lines)

for line in csv_lines:
    print line