合并后的文字:by python

时间:2015-09-23 08:22:06

标签: python

我收到了一个文本格式的文件:

a:
b(0.1),
c(0.33),
d:
e(0.21),
f(0.41),
g(0.5),
k(0.8),
h:
y(0.9),

我希望得到以下表格:

a: b(0.1), c(0.33)
d: e(0.21), f(0.41), g(0.5), k(0.8)
h: y(0.9)

在python语言中, 我试过了:

for line in menu:
    for i in line:
        if i == ":":

但我不知道我是否想知道打印(在i之前和之后的文字,直到遇到另一个我)作为一行。

也删除','在行尾

3 个答案:

答案 0 :(得分:3)

import re

one_line = ''.join(menu).replace('\n', ' ')
print re.sub(', ([a-z]+:)', r'\n\1', one_line)[:-1]

您可能需要调整one_line以更好地匹配您的输入。

答案 1 :(得分:1)

我不确定您是否要打印这些内容或实际操作该文件。但就印刷而言:

from __future__ import print_function
from itertools import tee, islice, chain, izip

def previous_and_next(some_iterable):
    prevs, items, nexts = tee(some_iterable, 3)
    prevs = chain([None], prevs)
    nexts = chain(islice(nexts, 1, None), [None])
    return izip(prevs, items, nexts)

with open('test.txt') as f:
    for i, (prev, line, next) in enumerate(previous_and_next(f)):
        if ":" in line and i != 0: #Add a newline before every ":" except the first.
            print()
        if not next or ":" in next: #Check if the next line is a semicolon, if so strip it. "not next" is need because if there is no next NoneType is returned.
            print(line.rstrip()[:-1], end=" ")
        else: #Otherwise just strip the newline and don't print any newline.
            print(line.rstrip(), end=" ")

使用this helper function

答案 2 :(得分:1)

这是一个使用OrderedDict存储' - 包含行作为键,以下行作为值的解决方案,直到找到下一个键。然后根据需要打印字典。

from collections import OrderedDict

data = OrderedDict()
key = False
for line in menu:
    if ':' in line:
        key = line.strip()
        data.update({line:[]})
    else:
        if key:
            data[key].append(line.strip(','))


for key in data:
    print(key,end=' ')

    if data[key][-1] != '':
        for item in data[key][:-1]:
            print(item, end=', ')
        print(data[key][-1])
    else:
        print(data[key][0])

给出:

a: b(0.1), c(0.33)
d: e(0.21), f(0.41), g(0.5), k(0.8)
h: y(0.9)