【问题标题】:Trim Array Element in List Comprehension在列表理解中修剪数组元素
【发布时间】:2018-09-28 21:19:56
【问题描述】:

改编自 Splitting a string by list of indices 的代码以将固定宽度数据加载到 Excel 工作表中,但不了解如何修剪 [List Comprehension] 函数最后一行中每个数组项的结果。

注意 - 除非打印行被注释掉,否则数据不会加载到 Excel 工作表中。

from itertools import tee, izip_longest
import openpyxl

def fixed_reader(df, data_start, data_end, indices, ws):
    with open(df, 'rb') as f:
        for line in range(0, data_start): next(f)
        for index, line in enumerate(f):
            if index == data_end: break
            start, end = tee(indices)
            next(end)
            print([line[i:j].rstrip('\r\n') for i,j in izip_longest(start, end)])      # <<<<<
            ws.append([line[i:j].rstrip('\r\n') for i,j in izip_longest(start, end)])  # <<<<<

wb = openpyxl.Workbook()
ws = wb.active
fixed_reader('FixedWidth.dat', 3, 7, [0,1,6,8], ws)
wb.save('FixedWidth.xlsx')

FixedWidth.dat

1C4PJLAB1FW506827
SMT701PD57J348217
1GTEG15X541150523
3GYFNCE39CS56512
1GCGK24N9PE171689
K   U G7FU046394G
1FTEF25NXKNA45683
1G2PF37R8FP298952
JC2UA2127B059 944 5D
JH2PC4080AK380263
1FT7W2BT7FEC79068

【问题讨论】:

  • 您能否提供.dat 文件第一行的预期输出?目前还不清楚你想要修剪什么。
  • ['K', 'U', 'G7', 'FU046394G'] -> ['K', 'U', 'G7', 'FU046394G']
  • 所以你只想从所有字符串中删除所有空格?
  • 只修剪每个数组元素两端的空格。

标签: python windows python-2.7 fixed-width


【解决方案1】:

您可以使用.strip() 修剪每个字符串两端的空格,或使用.strip(' ') 仅修剪空格。

line = line.rstrip('\r\n')
ws.append([line[i:j].strip(' ') for i,j in izip_longest(start, end)])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多