我运行了我的代码,并得到了2个这样的列表:
,我需要做的是将它们放在.csv文件中。 但我得到的输出看起来像这样丑陋:
那我该怎么解决这个问题?
代码:
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
答案 0 :(得分:1)
替换行:
data=[price(html),postcode(html)]
使用它:
data = zip(price(html), postcode(html))
答案 1 :(得分:1)
您可以使用zip
。更改:
data=[price(html),postcode(html)]
收件人:
data=zip(price(html),postcode(html))
答案 2 :(得分:0)
您可以使用字典吗? https://docs.python.org/3/tutorial/datastructures.html 将键设置为postCode,将值设置为价格
答案 3 :(得分:0)