利用Python requests库从网上下载txt文件时多出一个CR的处理

问题描述

1 的Reading word lists小节时,发现需要从thinkpython2/code/words.txt上下载words.txt文件。我不想利用复制-粘贴的方法构造该文件,想到之前学过的爬虫技术,于是写下如下代码:

import requests

r = requests.get('http://greenteapress.com/thinkpython2/code/words.txt')
# since abobe net use ISO-8859-1 encoding
r.encoding = 'utf-8'

# 写入外部文件
words = open('words.txt','w')
words.write(r.text)
words.close()

得到文件words.txt后,发现每个单词后面会跟个空行,我采用Notepad++的视图->显示符号->显示行尾符后,具体如下图所示:
多出cr
上述是个问题,怎样去掉多余的行?

解决方法

对上述文件的内容观察,发现是Macintosh格式,显示内容多出CR。为此我利用Notepad++的功能将其转换为Windows格式,如下图:
转换为Windows格式

转换后得到结果如下图所示:
转换Windows后
我用程序实际测试,在Windows系统下,Python的\n相当于CR LF。于是对于转换成Windows格式后的文件words.txt来说,我们需要做的是:将\n\n替换为\n。为此我使用如下代码(利用正则表达式):

# stripNewline.py
import re

fi = open('words.txt')
str = fi.read()
#str = 'nihao\n\n'
dnewlinePattern = re.compile(r'\n\n')
outStr = re.sub(dnewlinePattern,'\n',str)
fo = open('wordsOut.txt','w')
fo.write(outStr)
fo.close()
#print(repr(outStr))
fi.close()

得到的文件wordOut.txt满足了要求。如图:
满足要求的格式


  1. Allen B. Downey. Think Python: How to think like a computer scientist 2nd Edition. Sebastopol, CA: O’Reilly, 2016. ↩︎

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值