Python初学者:读取一个文件中的元素并使用它们修改另一个文件
我是一名经济学家,没有编程背景。我正在尝试学习如何使用python,因为有人告诉我,它对于解析来自网站的数据非常强大。目前,我仍在使用以下代码,如果有任何建议,我将不胜感激 首先,我编写了一段代码来解析此表中的数据: 我编写的代码如下:Python初学者:读取一个文件中的元素并使用它们修改另一个文件,python,loops,iteration,writing,Python,Loops,Iteration,Writing,我是一名经济学家,没有编程背景。我正在尝试学习如何使用python,因为有人告诉我,它对于解析来自网站的数据非常强大。目前,我仍在使用以下代码,如果有任何建议,我将不胜感激 首先,我编写了一段代码来解析此表中的数据: 我编写的代码如下: #!/usr/bin/env python from mechanize import Browser from BeautifulSoup import BeautifulSoup import urllib2, os def extract(soup)
#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import urllib2, os
def extract(soup):
table = soup.find("table", cellspacing=2)
for row in table.findAll('tr')[2:]:
col = row.findAll('td')
year = col[0].div.b.font.string
detrazione = col[1].div.b.font.string
ordinaria = col[2].div.b.font.string
principale = col[3].div.b.font.string
scopo = col[4].div.b.font.string
record = (year, detrazione, ordinaria, principale, scopo)
print >> outfile, "|".join(record)
outfile = open("milano.txt", "w")
br = Browser()
br.set_handle_robots(False)
url = "http://www.webifel.it/sifl/Tavola07.asp?comune=MILANO&cod_istat=15146"
page1 = br.open(url)
html1 = page1.read()
soup1 = BeautifulSoup(html1)
extract(soup1)
outfile.close()
代码读取表,只获取我需要的信息并创建一个txt文件。代码非常简单,但它完成了任务
我的问题现在开始了。我上面发布的url只是我需要解析数据的大约200个url之一。
所有URL仅由两个元素区分。使用上一个url:
唯一标识此页面的两个元素是米兰(城市名称)和15146(官僚代码)
我想做的是,首先,创建一个包含两列的文件:
#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import urllib2, os
import csv
def extract(soup):
table = soup.find("table", cellspacing=2)
for row in table.findAll('tr')[2:]:
col = row.findAll('td')
year = col[0].div.b.font.string
detrazione = col[1].div.b.font.string
ordinaria = col[2].div.b.font.string
principale = col[3].div.b.font.string
scopo = col[4].div.b.font.string
record = (year, detrazione, ordinaria, principale, scopo)
print >> outfile, "|".join(record)
citylist = csv.reader(open("citycodes.csv", "rU"), dialect = csv.excel)
for city in citylist:
outfile = open("%s.txt", "w") % city
br = Browser()
br.set_handle_robots(False)
url = "http://www.webifel.it/sifl/Tavola07.asp?comune=%s&cod_istat=%s" % city
page1 = br.open(url)
html1 = page1.read()
soup1 = BeautifulSoup(html1)
extract(soup1)
outfile.close()
其中citycodes.csv的格式如下
MILANO;12345
MODENA;67891
我得到以下错误:
Traceback (most recent call last):
File "modena2.py", line 25, in <module>
outfile = open("%s.txt", "w") % city
TypeError: unsupported operand type(s) for %: 'file' and 'list'
回溯(最近一次呼叫最后一次):
文件“modena2.py”,第25行,在
outfile=open(“%s.txt”,“w”)%city
TypeError:不支持%:“文件”和“列表”的操作数类型
再次感谢 如果文件为CSV格式,则可以使用来读取。然后只需使用生成查询字符串,并生成完整的URL。无需创建单独的文件,请使用python字典,其中有一个关系:city->code 请参阅:快速和肮脏:
import csv
citylist = csv.reader(open("citylist.csv"))
for city in citylist:
url = "http://www.webifel.it/sifl/Tavola07.asp?comune=%s&cod_istat=%s" % city
# open the page and extract the information
假设您的csv文件如下所示:
MILANO,15146
ROMA,12345
还有更强大的工具,如Ignacio提到的urllib.urlencode()
。但他们在这方面可能做得太过火了
祝贺你:你已经完成了从HTML中抓取数据的艰难工作。在列表上循环是很容易的一点。只需抓取基本内容
#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import urllib2, os
outfile = open("milano.txt", "w")
def extract(soup):
global outfile
table = soup.find("table", cellspacing=2)
for row in table.findAll('tr')[2:]:
col = row.findAll('td')
year = col[0].div.b.font.string
detrazione = col[1].div.b.font.string
ordinaria = col[2].div.b.font.string
principale = col[3].div.b.font.string
scopo = col[4].div.b.font.string
record = (year, detrazione, ordinaria, principale, scopo)
print >> outfile, "|".join(record)
br = Browser()
br.set_handle_robots(False)
# fill in your cities here anyway like
ListOfCityCodePairs = [('MILANO', 15146)]
for (city, code) in ListOfCityCodePairs:
url = "http://www.webifel.it/sifl/Tavola07.asp?comune=%s&cod_istat=d" % (city, code)
page1 = br.open(url)
html1 = page1.read()
soup1 = BeautifulSoup(html1)
extract(soup1)
outfile.close()
您需要解决一件小事: 这: 应该是这样的:
for city in citylist:
outfile = open("%s.txt" % city, "w")
# ^^^^^^
或者只是一个两元组列表:
[(“米兰”,“15146”),(“罗马”,“12345”),…]
。如果你构建了一个dict,你只需要对它调用.iteritems()
。输出文件是否也需要更改,或者所有的数据都要写入一个文件中。从您的示例中,我猜您也需要更改输出文件的名称,但我想我还是会问。是的,没错。我想为每个城市单独的txt文件。我根据其中一个答案修改了代码。但是我仍然有问题。请尝试以下操作:outfile=open(“%s.txt”%city[0],“w”)
非常感谢。考虑到你的建议,我编辑了这个问题。不过我还是有问题!再次感谢!谢谢。我将首先尝试从csv文件中读取这些对(城市、代码)。如果我不能解决我在问题的编辑版本中指出的问题,我肯定会采用你的方法。谢谢非常感谢你的回答。不幸的是,我对python的知识水平使得我很难从官方文档开始将这些工具应用于我的特定问题。
for city in citylist:
outfile = open("%s.txt" % city, "w")
# ^^^^^^