python解析文本

在看書的時候看到下面的內容覺得很難看,想把回車符去掉,換行符直接換行。思想是遍歷,遇到<cr>就直接索引加4,遇到<lf>換行並且索引加4,其他正常輸出。
文本如下:

GET /cs453/index.html HTTP/1.1<cr><lf>Host: gaia.cs.umass.edu<cr><lf>User-Agent: Mozilla/5.0 (Windows;U; Windows NT 5.1; en-US; rv:1.7.2) Gecko/20040804 Netscape/7.2 (ax) <cr><lf>Accept:ext/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,image/png,*/*;q=0.5<cr><lf>Accept-Language: en-us,en;q=0.5<cr><lf>Accept-Encoding: zip,deflate<cr><lf>Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7<cr><lf>Keep-Alive: 300<cr><lf>Connection:keep-alive<cr><lf><cr><lf>

發現自己不會寫代碼,先從讀文件開始吧:

f = open('data.txt', 'r')
data = f.read()
print(data)

這裏說python中讀取文件要這麼寫:

with open('/path/to/file', 'r') as f:
    data = f.read()

fro循環要怎麼寫呢?
通過序列索引迭代(參考):

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print '當前水果 :', fruits[index]

print第打印一個字符就要換行。
怎樣使 Python 輸出時不換行?

print('.', end='')

我想索引加3或者加4怎麼辦呢?發現python的for不能修改索引,可以用while。
python 中的for循環如何修改循環變量?

i = 0
length = len(seq)
while i < length:
    #just do it
    i += 1

終於寫出來了:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 22 22:00:31 2018

@author: itsc
"""

filename = 'data.txt'
f = open(filename, 'r')
data = f.read()

i = 0
length = len(data)-5
while i < length:
    if data[i:i+4] == '<cr>':
        i += 3
    elif data[i:i+4] == '<lf>':
        print()
        i += 3
    else:
        print(data[i], end='')
    i += 1

輸出:

GET /cs453/index.html HTTP/1.1
Host: gaia.cs.umass.edu
User-Agent: Mozilla/5.0 (Windows;U; Windows NT 5.1; en-US; rv:1.7.2) Gecko/20040804 Netscape/7.2 (ax) 
Accept:ext/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: zip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection:keep-alive

真是菜。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章