如何删除数组中的部分文本?

时间:2019-06-21 20:04:47

标签: python

我是Python的新手

我有这个txt:

======== Data: 00:05:08.627012 =========            

1900-01-01 00:05:08.627012 ; 0 ; 1.16198 ; 10000000.0
1900-01-01 00:05:08.627012 ; 1 ; 1.16232 ; 10000000.0

========= Data: 00:05:12.721536 =========           

1900-01-01 00:05:08.627012 ; 0 ; 1.16198 ; 10000000.0
1900-01-01 00:05:12.721536 ; 0 ; 1.16209 ; 1000000.0
1900-01-01 00:05:08.627012 ; 1 ; 1.16232 ; 10000000.0

我需要删除“ 1900-01-01”,但要节省时间,并将0更改为Bid,将1更改为Ask

我和平相处,无法弄清楚下一步该怎么做

readyColumns = []

for row in lines:
    row = row.strip()
    rowsAsArray = row.split(';')
    for element in rowsAsArray:
        element = element.split(';')
        print(element)

2 个答案:

答案 0 :(得分:1)

如果1900-01-01始终位于开头且为常数,则可以截取前11个字符。要替换01并使用replace(如果我没听错的话),例如:

row = "1900-01-01 00:05:08.627012 ; 1 ; 1.16232 ; 10000000.0"
row[11:].replace('; 0 ;', '; Bid ;').replace('; 1 ;', '; Ask ;')

>>> '00:05:08.627012 ; Ask ; 1.16232 ; 10000000.0'

答案 1 :(得分:0)

lines_block = '''======== Data: 00:05:08.627012 =========            

1900-01-01 00:05:08.627012 ; 0 ; 1.16198 ; 10000000.0
1900-01-01 00:05:08.627012 ; 1 ; 1.16232 ; 10000000.0

========= Data: 00:05:12.721536 =========           

1900-01-01 00:05:08.627012 ; 0 ; 1.16198 ; 10000000.0
1900-01-01 00:05:12.721536 ; 0 ; 1.16209 ; 1000000.0
1900-01-01 00:05:08.627012 ; 1 ; 1.16232 ; 10000000.0'''

lines = lines_block.split('\n')
new_lines = []
for line in lines:
    if line.startswith('1900-01-01'):
        fields = line.split(' ; ')
        fields[0] = fields[0][10:]
        fields[1] = 'Bid' if fields[1] == '0' else 'Ask'
        new_line = ' ; '.join(fields)
        new_lines.append(new_line)
    else:
        new_lines.append(line)

for line in new_lines:
    print(line)

输出

======== Data: 00:05:08.627012 =========            

 00:05:08.627012 ; Bid ; 1.16198 ; 10000000.0
 00:05:08.627012 ; Ask ; 1.16232 ; 10000000.0

========= Data: 00:05:12.721536 =========           

 00:05:08.627012 ; Bid ; 1.16198 ; 10000000.0
 00:05:12.721536 ; Bid ; 1.16209 ; 1000000.0
 00:05:08.627012 ; Ask ; 1.16232 ; 10000000.0