【问题标题】:TypeError: cannot use a string pattern on a bytes-like object [duplicate]TypeError:不能在类似字节的对象上使用字符串模式[重复]
【发布时间】:2016-06-03 12:43:30
【问题描述】:

无法找出此错误消息。有人可以帮忙吗? re.findall 行出现错误。

import re, urllib.request
infile = open('phone_numbers.txt')

for line in infile:
    line = line.strip()

    area=line[0:3]
    area1=line[5:7]
    area2=line[8:12]

    xyz = 'http://usreversephonedirectory.com/results.php?areacode='+ area +'&phone1='+ area1 +'&phone2='+ area2 +'&imageField.x=193&imageField.y=16&type=phone&Search=Search&redir_page=results%2Fphone%2F'

    print(area + area1 + area2)

    page = urllib.request.urlopen(xyz)
    text = page.read()
    text = text.strip()

    location = re.findall('>Location:</strong>(.+)</span><br/>            <span><strong>Line', text)

    print(line + '|' + location[0])

infile.close()

【问题讨论】:

  • 请修正代码的顶部和底部。有行被排除
  • 很抱歉。马上修复
  • 能否请您提供一个示例或完整的phone_numbers.txt
  • 我认为您的文本是以二进制形式读入的,您需要将其转换为字符串。尝试在您的文本获取行中添加.decode('utf-8')text = text.strip().decode('utf-8')

标签: python


【解决方案1】:

正如@Ben 所说,您的文本将被读取为二进制文件。使用他的解码方法text.strip() 错误消失了。我使用的方法如下。您可能想从美学角度修复它的输出。希望这会有所帮助!

$ echo "1 (800) 233-2742" >> phone_numbers.txt # Put a random number into phone_numbers.txt
$ python lookup.py                             # Run the fixed program
1 (0)233-                                      # Output line 1
1 (800) 233-2742| ,                            # Output line 2
$                                              # Done

代码(更新):

import re, urllib.request
infile = open('phone_numbers.txt')

for line in infile:
    line = line.strip()

    area=line[0:3]
    area1=line[5:7]
    area2=line[8:12]

xyz = 'http://usreversephonedirectory.com/results.php?areacode='+ area +'&phone1='+ area1 +'&phone2='+ area2 +'&imageField.x=193&imageField.y=16&type=phone&Search=Search&redir_page=results%2Fphone%2F'

print(area + area1 + area2)

page = urllib.request.urlopen(xyz)
text = page.read()
text = text.strip().decode('utf-8')

location = re.findall('>Location:</strong>(.+)</span><br/>            <span><strong>Line', text)

print(line + '|' + location[0])

infile.close()

【讨论】:

  • 感谢您的帮助!我遇到了另一个问题...为什么我的代码没有从网站中提取位置?不确定在 location = re.findall(... 中使用什么来获取正确的位置数据。
猜你喜欢
  • 2014-02-21
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 2015-09-10
  • 1970-01-01
相关资源
最近更新 更多