标签: python-unicode

UnicodeDecodeError:'ascii'编解码器无法解码位置304中0xc3中的字节:序数不在范围内(128)

我刚刚离开PC工作(使用Python 2.7)并且有一个我刚刚完成的脚本(下面再现).它在工作中运行良好,我只是想添加一两件事.但我回到家并使用我的Mac版Python(3.2.2),我收到以下错误:

Traceback (most recent call last):
  File "/Users/Downloads/sda/alias.py", line 25, in <module>
    for row_2 in in_csv:
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 304: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我的代码在这里:

import csv
inname = "Fund_Aliases.csv"
outname = "output.csv"

def first_word(value):
    return value.split(" ", 1)[0]

with open(inname, "r") as infile:
    with open(outname, "w") as out file:
      in_csv = csv.reader(infile)
      out_csv = csv.writer(outfile)

     column_names = next(in_csv)
     out_csv.writerow(column_names)

      id_index = column_names.index("id")
      name_index …
Run Code Online (Sandbox Code Playgroud)

python macos syntax-error python-unicode

4
推荐指数
1
解决办法
1万
查看次数

我如何知道Python的unicode函数识别的所有支持的编码

Python 有一个unicode内置函数可以将字节流转换为 unicode 字符串。

在此输入图像描述

我只是希望我可以查询我的系统上所有可用的编码。但如何。

这个问题的原因是:有人使用 MAC OS X 向我发送了一封内容编码为“iso-2022-cn”的电子邮件,我发现 Windows 7 上的 Python 2.7 无法识别该编码。

>>> print unicode(bs2022, 'iso-2022-cn')

Traceback (most recent call last):
  File "<pyshell#97>", line 1, in <module>
    print unicode(bs2022, 'iso-2022-cn')
LookupError: unknown encoding: iso-2022-cn
Run Code Online (Sandbox Code Playgroud)

所以我想通过查看Python可以支持的所有编码来找出Python是否对“iso-2022-cn”使用了不同的名称。

python character-encoding python-unicode

4
推荐指数
1
解决办法
1436
查看次数

无法在 python selenium 脚本中使用带有特殊字符“$”的密码

示例脚本:

\n\n
# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nimport os\n\n#credentials\nUSERNAME = \'##########\'\nPASSWORD = \'#####$####\xe2\x80\x8b\'\n\n#load profile\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference(\'browser.download.folderList\', 2)  # custom location\nprofile.set_preference(\'browser.download.manager.showWhenStarting\', False)\nprofile.set_preference(\'browser.download.dir\', os.getcwd())\n\n# following properties to suppress download popup screen\nprofile.set_preference("browser.helperApps.neverAsk.openFile", "text/csv")\nprofile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv")\n\n# initialise driver with above profile\ndriver = webdriver.Firefox(profile)\n\n\n#make the request to the url\ndriver.get(\'https://api.instagram.com/oauth/authorize/?client_id=#################&redirect_uri=#############&response_type=token\')\n#browser.current_url\ndriver.implicitly_wait(5)\n\n#Enter username and password\nUsername = driver.find_element_by_css_selector(\'#id_username\')\nUsername.send_keys(USERNAME)\n\nPassword = driver.find_element_by_css_selector(\'#id_password\')\nPassword.send_keys(PASSWORD)\n\n#SignIn button click\nSignIn = driver.find_element_by_css_selector(\'.button-green\').click()\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如你所看到的,我正在尝试验证 Instagram 应用程序。我无法传递具有特殊字符“$”的正确密码值。我收到以下错误。

\n\n
C:\\Python27\\python.exe "D:/Projects/#####/Instagram Data Extraction/ETL_Scripts/Instagram_auth.py"\nTraceback (most recent call last):\n  File "D:/Projects/######/Instagram Data Extraction/ETL_Scripts/Instagram_auth.py", line 35, in <module>\n    Password.send_keys(PASSWORD)\n  File "C:\\Python27\\lib\\site-packages\\selenium\\webdriver\\remote\\webelement.py", …
Run Code Online (Sandbox Code Playgroud)

python selenium decode utf-8 python-unicode

4
推荐指数
1
解决办法
1815
查看次数

Python默认字符串编码

Python 何时、何地以及如何将编码隐式应用于字符串或进行隐式转码(转换)?

那些“默认”(即隐含)编码是什么?

例如,什么是编码:

python character-encoding python-2.x python-3.x python-unicode

4
推荐指数
1
解决办法
6077
查看次数

python:动态类型转换 - unicode 对象到 python 对象的转换

这是我在数据管道项目中面临的一个问题。我有 2 个数据源。一个包含所有用户数据,另一个包含我们必须从用户数据处理到输出的所有列的元数据。

所以python很适合动态类型转换,就像我说的

a = float
b = "25.123"
c = a(b)
print(c)
>> 25.123
Run Code Online (Sandbox Code Playgroud)

这就是我想要做的,我想动态键入强制转换值以便正确处理它们。该类型是从元数据数据源中检索的。问题是当我对元数据进行 django 模型查询时,我得到了 unicode 对象。

a = model.objects.filter(id = 'id') # get the type variable from the meta-data
a = a[0]['type']
print(a)
>> u'float'
a("123.123")
>> TypeError: 'unicode' object is not callable
Run Code Online (Sandbox Code Playgroud)

我如何将这个 u'float' 转换为 float ?这种方法有更好的选择吗?我检查了这个,但它不起作用

对所有建议开放

python type-conversion django-models dynamictype python-unicode

4
推荐指数
1
解决办法
1442
查看次数

用 html 实体替换重音字符

我正在尝试自动执行一系列查询,但是,我需要将带有重音符号的字符替换为相应的 html 实体。\n它需要在 Python3 中

\n

例子:

\n
v\xc3\xa8lit \n[needs to become] \nv&egrave;lit\n
Run Code Online (Sandbox Code Playgroud)\n

问题是,每当我尝试执行 a 时word.replace,它都找不到。

\n

这:

\n
if u'\xc3\xa8' in sentence:\n    print(u'Found \xc3\xa8')\n
Run Code Online (Sandbox Code Playgroud)\n

工作并找到“\xc3\xa8”,但执行以下操作:

\n
word.replace('\xc3\xa8','&egrave;')\n
Run Code Online (Sandbox Code Playgroud)\n

什么都不做。

\n

python replace python-3.x python-unicode iso-8859-15

4
推荐指数
1
解决办法
2928
查看次数

从文本中删除所有表情符号

这个问题在这里被问到Python : How to remove all emojis without a solution,我已经朝着解决方案迈出了一步。但需要帮助完成它。

我从表情符号网站上获取了所有表情符号十六进制代码点:https : //www.unicode.org/emoji/charts/emoji-ordering.txt

然后我像这样读入文件:

file = open('emoji-ordering.txt')
temp = file.readline()

final_list = []

while temp != '':
    #print(temp)
    if not temp[0] == '#' :
            utf_8_values = ((temp.split(';')[0]).rstrip()).split(' ')
            values = ["u\\"+(word[0]+((8 - len(word[2:]))*'0' + word[2:]).rstrip()) for word in utf_8_values]
            #print(values[0])
            final_list = final_list + values
    temp = file.readline()

print(final_list)
Run Code Online (Sandbox Code Playgroud)

我希望这会给我 unicode 文字。不是,我的目标是获得 unicode 文字,这样我就可以使用上一个问题的部分解决方案,并能够排除所有表情符号。任何想法我们需要什么才能获得解决方案?

python unicode-string python-3.x emoji python-unicode

4
推荐指数
2
解决办法
9352
查看次数

将结果从 python 写入 csv 文件 [UnicodeEncodeError: 'charmap' codec can't encode character

我一直在尝试编写一个脚本,该脚本可能会从定义的 YouTube 视频的评论部分中删除用户名列表,并将这些用户名粘贴到 .csv 文件中。

这是脚本:

from selenium import webdriver
import time
import csv
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as soup
driver=webdriver.Chrome()
driver.get('https://www.youtube.com/watch?v=VIDEOURL')
time.sleep(5)
driver.execute_script("window.scrollTo(0, 500)")
time.sleep(3)
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.END)
time.sleep(5)
scroll_time = 40
for num in range(0, scroll_time):
    html.send_keys(Keys.PAGE_DOWN)
for elem in driver.find_elements_by_xpath('//span[@class="style-scope ytd-comment-renderer"]'):
    print(elem.text)
    with open('usernames.csv', 'w') as f:
        p = csv.writer(f)
        p.writerows(str(elem.text));
Run Code Online (Sandbox Code Playgroud)

它不断抛出第 19 行的错误:

return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u30b9' in position 0: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)

我在这里读到这可能与 Windows …

python csv character-encoding python-3.x python-unicode

4
推荐指数
1
解决办法
2635
查看次数

影响编码、解码和打印的 python 设置列表是什么?

当我遇到 unicode 打印问题时,我想知道应该检查什么。在我的特定情况下,我使用一个已安装的模块,该模块使用错误的编解码器打印 unicode 编码字符。

在各种情况下,有几个不同的地方会影响 python 编码和解码。具体来说,Python 在不同情况下如何处理可打印数据。

有些事情是最重要的:

  • 一般环境变量LC_ALL,LANG
  • Pythonsys模块设置sys.getdefaultencoding()

我还忘记了什么?


我只对 python 3 感兴趣。

python unicode localization utf python-unicode

4
推荐指数
1
解决办法
570
查看次数

使用 usecols 时 pandas.read_excel 错误

我在从 Excel 文件读取数据时遇到一些问题。\nExcel 文件包含带有 unicode 字符的列名称。

\n\n

由于一些自动化原因,我需要将usecols参数传递给 pandas.read_excel 函数。

\n\n

问题是,当我不使用usecols参数时,数据加载时不会出现错误。

\n\n

这是代码:

\n\n
import pandas as pd\n\ndf = pd.read_excel(file)\ndf.colums\n\nIndex([u\'col1\', u\'col2\', u\'col3\', u\'col with unicode \xc3\xa0\', u\'col4\'], dtype=\'object\')\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果我使用 usecols:

\n\n
COLUMNS = [\'col1\', \'col2\', \'col with unicode \xc3\xa0\']\ndf = pd.read_excel(file, usecols = COLUMNS)\n
Run Code Online (Sandbox Code Playgroud)\n\n

我收到以下错误:

\n\n
ValueError: Usecols do not match columns, columns expected but not found: [\'col with unicode \\xc3\\xa0\']\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用encoding = \'utf-8\'read_excel 作为参数并不能解决问题,并且还对 COLUMNS 元素进行编码。

\n\n

编辑:这里是完整的错误窗口。

\n\n …

python python-2.7 pandas python-unicode pandas-datareader

4
推荐指数
2
解决办法
4万
查看次数