Skip to main content
 首页 » 编程设计

python之将 BeautifulSoup 中的文本写入文件

2024年11月01日9傻小

我想解析 http://en.wikipedia.org/wiki/List_of_circulating_currencies 中的货币表.问题是我没有得到正确格式的输出。我希望输出的形式为:

country currency 

在使用多种货币的情况下,货币应位于下一行或前一种货币之后的空格中。这是我能走多远

from bs4 import BeautifulSoup 
 
import urllib2 
url="http://en.wikipedia.org/wiki/List_of_circulating_currencies" 
soup=BeautifulSoup(urllib2.urlopen(url).read()) 
i=1 
fr=open("out.txt","w") 
for row in soup.findAll('table')[0].findAll('tr'): 
    if i==1: 
        i+=1 
        continue 
 
 
    temp_row=row.findAll('td') 
    print len(temp_row) 
    """Handling the case for multiple currencies""" 
    if(len(temp_row)==5): 
        ans=row.findAll('td')[0].findAll('a') 
        if len(ans)==0 : 
            ans=row.findAll('td')[0].contents 
        else : 
            ans=row.findAll('td')[0].findAll('a')[0].contents 
        fr.write("      "+str(ans)+"\n") 
    else: 
        first=row.findAll('td')[0].findAll('a')[0].contents 
 
        ans=row.findAll('td')[1].findAll('a') 
        if len(ans)==0 : 
            ans=row.findAll('td')[1].contents 
        else : 
            ans=row.findAll('td')[1].findAll('a')[0].contents 
    #print first 
        fr.write(str(first)+"    "+str(ans)+"\n") 

问题是当我使用 contents[0] 而不是它给出的内容时我想要字符串:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 15: ordinal not in range(128) 

错误我也没有得到准确格式的输出。文件 out.txt 必须由其他一些用 VB 编写的程序读取,因此我希望文件格式尽可能接近指定的格式。也请帮我清理代码。

更新:

使用编码时出现以下错误:

 File "D:/scrap.py", line 33, in <module> 
    first = first.encode('ascii', 'ignore') 
  File "C:\Python27\lib\site-packages\bs4\element.py", line 992, in encode 
    u = self.decode(indent_level, encoding, formatter) 
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1056, in decode 
    indent_space = (' ' * (indent_level - 1)) 
TypeError: unsupported operand type(s) for -: 'str' and 'int' 

更新:在开头添加了以下几行以使其工作

import sys 
reload(sys) 
sys.setdefaultencoding("utf-8") 

请您参考如下方法:

如果您可以在文件中使用 utf 字符,则可以使用 encode('utf8') 将 unicode 对象转换为 utf 编码的字符串。