【问题标题】:Unsupported operand type for %: 'file' and 'unicode' [duplicate]% 不支持的操作数类型:'file' 和 'unicode' [重复]
【发布时间】:2016-03-21 19:02:11
【问题描述】:

我正在尝试收集有关我所在地区的大量人口普查数据,从一个链接开始以获取正确的代码。最初,我想获取页面的标题并将页面中的数据存储在以标题命名的 txt 文件中。

例如,在这种情况下,Census Block 970900-1-001 in Cortland County, New York 将是 txt 文件的标题。但是,当我尝试使用% variable 方法执行此操作时,它给了我错误Unsupported operand type for %: 'file' and 'unicode'。我理解错误消息 - 我的问题是,我怎样才能实现我想要的功能,或者它甚至可能吗?

到目前为止编写的代码:

from bs4 import BeautifulSoup
from urllib2 import urlopen

links = ['http://www.usa.com/NY0239709001001.html']

def block():
    link = links[0]
    html = urlopen(link)
    soup = BeautifulSoup(html.read(),'lxml')
    h1 = soup.find('h1').text
    print(h1)
    f = open('%s.txt','w') % h1
    f.write(h1)

预期输出: 创建一个名为Census Block 970900-1-001 in Cortland County, New York.txt的文件

实际输出:

Unsupported operand type for %: 'file' and 'unicode'

【问题讨论】:

    标签: python unicode


    【解决方案1】:

    % h1放在open()里面:

    f = open('%s.txt' % h1, 'w')
    

    【讨论】:

      【解决方案2】:

      我猜你想要:

      open('%s.txt' % h1, 'w')

      即您想使用字符串格式生成要传递给open 的文件名——您不想打开一个名为'%s.txt' 的文件。

      【讨论】:

      • 天啊!谢谢,@mgilson!
      • @n1c9 -- 发生在我们最好的人身上。诀窍是学习如何仔细阅读回溯。我无法告诉你我浪费了多少个小时来跟踪如果我稍微仔细阅读回溯就很容易找到的错误。 . .
      猜你喜欢
      • 2010-11-16
      • 1970-01-01
      • 2012-12-27
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      相关资源
      最近更新 更多