python - 如何在python中排除BMP中不存在的字符?

标签 python python-3.x utf-8 urllib

这是一个提供术语并抓取的应用程序 Urban Dictionary并返回页面中的第一个含义。 这是我到目前为止的代码:

import re
import urllib.request

term = input('Enter a word: ')
url = "https://www.urbandictionary.com/define.php?term=" + term

rawData = urllib.request.urlopen(url).read()
decodedData = rawData.decode("utf-8")

x = re.search('div class="meaning"', rawData)
start = x.start()
end = x.end()
result = rawData[start:end]
print(result)

但我收到以下错误

    Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    print(decodedData)
  File "~\Python\Python35-32\lib\idlelib\PyShell.py", line 1344, in write
    return self.shell.write(s, self.tags)
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 95889-95889: Non-BMP character not supported in Tk

如何排除无法解码的字符?

最佳答案

好的,要解决您的问题,您只需实际使用解码后的数据即可。目前您正在解码数据,但随后您使用 rawData:

import re
import urllib.request

term = input('Enter a word: ')
url = "https://www.urbandictionary.com/define.php?term=" + term

rawData = urllib.request.urlopen(url).read()
decodedData = rawData.decode("utf-8")

x = re.search('div class="meaning"', decodedData)
start = x.start()
end = x.end()
result = decodedData[start:end]
print(result)

应该可以了。如果这不起作用,请发布一个引发此错误的示例单词。 (顺便说一下,这段代码不会产生你想要的输出)

关于python - 如何在python中排除BMP中不存在的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446194/

相关文章:

python - 在 python 解释器中输入一个对象的名称 - 它调用什么方法?

iphone - 如何获取 NSString 的 UTF8 二进制值

python - 创建和使用坐标网格

python - Django - 如何获取输入列表,选择使用 javascript 动态创建的?

python - 所有 O(1) 函数的运行时间完全相同。对或错?

PHP Streaming CSV 始终添加 UTF-8 BOM

mysql - UTF-8 仅在 Grails 数据库表中

python - 如何从字符串中提取 float

python-3.x - 将列中的所有重复值作为 pandas 中的单个值

python - Pandas:如果在 groupby 之后基于其他列存在重复项,则根据特定列上给出的权重保留特定行