Home  >  Q&A  >  body text

url - 用Python从网页提取的文本,转换成str格式后,怎么逐行处理呢?

用Python从url上抓取文本之后,想对文本进行逐行的解析,老出错,debug时发现每一行都是一个字母,不是一句完整的话。想不太明白,请大神指教。 fhand 和 line 的 type 都是 str

import urllib.request

fhand = urllib.request.urlopen('http://www.pythonlearn.com/code/mbox.txt').read().decode()
a=0
print (fhand)

for line in fhand:

if a < 5:
    print (type(line) )
    print (line)
    a=a+1
迷茫迷茫2712 days ago407

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-18 09:08:25

    fhand = urllib.request.urlopen('http://www.pythonlearn.com/code/mbox.txt').readlines()
    
    for line in fhand:
      # ...

    or:

    fhand = urllib.request.urlopen('http://www.pythonlearn.com/code/mbox.txt').read().decode()
    
    for line in fhand.split('\n'):
      # ...

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:08:25

    for line in Ghana.split(“\n”)

    reply
    0
  • Cancelreply