2016-09-15 60 views
1

我有下面的代码,它将从网站上获取一些汉字数据。列表理解和汉字项目

import csv 
import requests 
from bs4 import BeautifulSoup 

url = "http://www.hkcpast.net/cpast_homepage/xyzbforms/BetMatchDetails.asp?tBetDate=2016/9/11" 

r = requests.get(url) 
soup = BeautifulSoup(r.content, "html.parser") 

for a in soup.find_all('html'): 
    a.decompose() 

list = [] 
for row in soup.find_all('tr'): 
    cols = row.find_all('td') 
    for col in cols: 
     if len(col) > 0: 
      list.append(col.text.encode('utf-8').strip()) 

对于现在的结果是这样的:

[1, x, y, z, 2, x, y, z, 3, x, y, z] 

我的问题是要创建从列表,其是由多个(1,2,3,4分离一些子列表。,5 ...)

使得结果将是这样的:。

[1, x, y, z] 
[2, x, y, z] 
[3, x, y, z] 

的这个最终目的是写入每个子列表作为csv文件中的一行。首先将列表分成每个条目然后写入一个csv文件是否有意义?

+0

请坚持*每个问题*一个问题。然而,你描述的两个问题都太模糊了。也许你可以为我们提供一些样本输入和预期的输出?后者只是一个编码问题;您将数据编码为UTF-8,因此在打印或列出时,您会在输出中看到'\ xhh'字节表示。这很正常。 –

+0

我编辑了这个问题,只剩下一个问题了。我怎样才能从具有特定要求的列表中创建子列表。 –

回答

0

代码的直译会是什么样子:

list = [] 
for row in soup.find_all('tr'): 
    cols = row.find_all('td') 
    for col in cols: 
     if len(col) = 0: 
      continue # Save some indentation 
     txt = col.text.encode('utf-8').strip() 
     try: 
      _ = int(txt) 
      # txt is an int. Append new sub-list 
      list.append([txt]) 
     except ValueError: 
      # txt is not an int, append it to the end of previous sub-list 
      list[-1].append(txt) 

(请注意,如果第一项是不是int,这将可怕的失败!)

不过,我怀疑你真的想为表中的每一行创建一个新的子列表。