合并文本后:按python

2024-04-16 13:28:46 发布

您现在位置: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 == ":":

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

同时删除行末尾的“,”


Tags: in语言forifline表格menu文字
3条回答

我不确定你是想打印这些东西还是真的要处理文件。但如果只是打印:

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。你知道吗

import re

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

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

这里是一个使用orderedict存储“:”的解决方案,其中包含行作为键,下面的行作为值,直到找到下一个键为止。那就把字典印成你喜欢的样子。你知道吗

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)

相关问题 更多 >