我运行了代码,并得到了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
最佳答案
您可以使用zip
。更改:
data=[price(html),postcode(html)]
至:
data=zip(price(html),postcode(html))
关于python - 如何在2列而不是2个数组中写入2个项目列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51879628/