如何在两列而不是两个数组中编写两个项目列表?

2024-07-04 08:02:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我运行了我的代码,得到了如下两个列表:

enter image description here

我需要做的是把它们放在一个.csv文件中。 但我得到的结果看起来很难看:

enter image description here

正确的答案应该是这样的: enter image description here

那我该怎么解决这个问题呢

代码:

from urllib.request import urlopen
import urllib
import re
import csv

def main():
    html = urlopen("https://www.realestate.com.au/rent/with-1-bedroom-in-perth+-+greater+region%2c+wa/list-1?maxBeds=1&source=location-search").read().decode('utf-8')
    csvfile=open('price.csv','w',newline='')
    #### check
    ##print(price(html))
    ##print(postcode(html))
    #### end check
    writer=csv.writer(csvfile)
    writer.writerow(['Postcode','Price'])
    data=[price(html),postcode(html)]
    writer.writerows(data)
    csvfile.close()

def price(page):
    priceTextReg=re.compile(r"priceText\">(.+?)<")
    priceText = re.findall(priceTextReg,page)
    p1=[]
    for i in range(20):  ## we just need the first 20 items
        priceReg=re.compile(r"\d+")
        price=re.findall(priceReg,priceText[i])
        p1.append(price[0])  
    return p1

def postcode(page):
    postcodeTextReg=re.compile(r"alt=.+?, WA (.+?)' title=")
    postcodeText=re.findall(postcodeTextReg,page)
    p2=[]
    for i in range(20):
        postcode=postcodeText[i]
        p2.append(postcode)
    return p2

Tags: csvcsvfileinimportredefhtmlpage
3条回答

您可以使用zip。更改:

data=[price(html),postcode(html)]

收件人:

data=zip(price(html),postcode(html))

你会用字典吗https://docs.python.org/3/tutorial/datastructures.html 将键设置为邮政编码,将值设置为价格

更换管路:

data=[price(html),postcode(html)]

有了它:

data = zip(price(html), postcode(html))

相关问题 更多 >

    热门问题