简体   繁体   English

如何拆分此字符串?

[英]How do I split this string up?

...    
    1947q2        -0.6
    1947q3        -0.3
    1947q4         6.2
    1948q1        16.5
...

How do I get this text file into a list? 如何将此文本文件放入列表中? I'm having problems with the spacing between the year and corresponding values. 我对年份和相应值之间的间距有问题。

This is what I have so far: 这是我到目前为止:

data = []

for line in open("file"):
    if '1947' in line:
        sl = line.split('       ')
        data.append((sl[0], sl[1]))

print data

Just using split() without arguments splits by whitespace, and eats consecutive whitespace: 只使用不带参数的split()按空格分割,并吃掉连续的空格:

>>> s='    1947q2        -0.6'
>>> s.split()
['1947q2', '-0.6']
data = []

with open("file") as fin:
    for line in fin:
        data.append(tuple(line.split()))

print data

一个班轮使用列表理解和几个快捷键来读取数据:

data = [line.split() for line in open('path/to/file', 'rt')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM