使用Python编写/解析固定宽度的文件 [英] Writing/parsing a fixed width file using Python
问题描述
我是Python的新手,我正在寻找用它来编写我们的供应商所需的一些毛茸茸的EDI内容.
I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires.
基本上,他们需要一个80个字符的固定宽度的文本文件,该字段的某些块"包含数据,而其他部分则留空.我有文档,所以我知道每个块"的长度.我回来的响应更容易解析,因为它已经有了数据,并且我可以使用Python的切片"来提取我需要的内容,但是我无法分配给切片-我已经尝试过了,因为听起来很不错解决方案,由于Python字符串是不可变的,因此无效:)
Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :)
就像我说的那样,我确实是Python的新手,但我对学习它感到很兴奋:)我将如何去做呢?理想情况下,我希望能够说出10-20的范围等于"Foo",并使其具有7个其他空格字符的字符串"Foo"(假设该字段的长度为10),并且该范围为是80个字符较大的字段的一部分,但我不确定该怎么做.
Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking.
推荐答案
You don't need to assign to slices, just build the string using % formatting
.
具有3个数据项的固定格式的示例:
An example with a fixed format for 3 data items:
>>> fmt="%4s%10s%10s"
>>> fmt % (1,"ONE",2)
' 1 ONE 2'
>>>
同样,数据随附的字段宽度:
Same thing, field width supplied with the data:
>>> fmt2 = "%*s%*s%*s"
>>> fmt2 % (4,1, 10,"ONE", 10,2)
' 1 ONE 2'
>>>
分隔数据和字段宽度,并使用zip()
和str.join()
技巧:
Separating data and field widths, and using zip()
and str.join()
tricks:
>>> widths=(4,10,10)
>>> items=(1,"ONE",2)
>>> "".join("%*s" % i for i in zip(widths, items))
' 1 ONE 2'
>>>
这篇关于使用Python编写/解析固定宽度的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!