我刚刚离开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 有一个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”使用了不同的名称。
示例脚本:
\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()\nRun Code Online (Sandbox Code Playgroud)\n\n正如你所看到的,我正在尝试验证 Instagram 应用程序。我无法传递具有特殊字符“$”的正确密码值。我收到以下错误。
\n\nC:\\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 何时、何地以及如何将编码隐式应用于字符串或进行隐式转码(转换)?
那些“默认”(即隐含)编码是什么?
例如,什么是编码:
字符串文字?
s = "Byte string with national characters"
us = u"Unicode string with national characters"
Run Code Online (Sandbox Code Playgroud)
类型转换为 Unicode 或从 Unicode 转换时的字节字符串?
data = unicode(random_byte_string)
Run Code Online (Sandbox Code Playgroud)
何时将字节和 Unicode 字符串写入文件或终端?
print(open("The full text of War and Peace.txt").read())
Run Code Online (Sandbox Code Playgroud)
python character-encoding python-2.x python-3.x python-unicode
这是我在数据管道项目中面临的一个问题。我有 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
我正在尝试自动执行一系列查询,但是,我需要将带有重音符号的字符替换为相应的 html 实体。\n它需要在 Python3 中
\n例子:
\nv\xc3\xa8lit \n[needs to become] \nvèlit\nRun Code Online (Sandbox Code Playgroud)\n问题是,每当我尝试执行 a 时word.replace,它都找不到。
这:
\nif u'\xc3\xa8' in sentence:\n print(u'Found \xc3\xa8')\nRun Code Online (Sandbox Code Playgroud)\n工作并找到“\xc3\xa8”,但执行以下操作:
\nword.replace('\xc3\xa8','è')\nRun Code Online (Sandbox Code Playgroud)\n什么都不做。
\n这个问题在这里被问到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 文字,这样我就可以使用上一个问题的部分解决方案,并能够排除所有表情符号。任何想法我们需要什么才能获得解决方案?
我一直在尝试编写一个脚本,该脚本可能会从定义的 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 …
当我遇到 unicode 打印问题时,我想知道应该检查什么。在我的特定情况下,我使用一个已安装的模块,该模块使用错误的编解码器打印 unicode 编码字符。
在各种情况下,有几个不同的地方会影响 python 编码和解码。具体来说,Python 在不同情况下如何处理可打印数据。
有些事情是最重要的:
LC_ALL,LANGsys模块设置sys.getdefaultencoding()我还忘记了什么?
我只对 python 3 感兴趣。
我在从 Excel 文件读取数据时遇到一些问题。\nExcel 文件包含带有 unicode 字符的列名称。
\n\n由于一些自动化原因,我需要将usecols参数传递给 pandas.read_excel 函数。
\n\n问题是,当我不使用usecols参数时,数据加载时不会出现错误。
\n\n这是代码:
\n\nimport 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\')\nRun Code Online (Sandbox Code Playgroud)\n\n如果我使用 usecols:
\n\nCOLUMNS = [\'col1\', \'col2\', \'col with unicode \xc3\xa0\']\ndf = pd.read_excel(file, usecols = COLUMNS)\nRun Code Online (Sandbox Code Playgroud)\n\n我收到以下错误:
\n\nValueError: Usecols do not match columns, columns expected but not found: [\'col with unicode \\xc3\\xa0\']\nRun Code Online (Sandbox Code Playgroud)\n\n使用encoding = \'utf-8\'read_excel 作为参数并不能解决问题,并且还对 COLUMNS 元素进行编码。
编辑:这里是完整的错误窗口。
\n\n …python ×10
python-unicode ×10
python-3.x ×4
csv ×1
decode ×1
dynamictype ×1
emoji ×1
iso-8859-15 ×1
localization ×1
macos ×1
pandas ×1
python-2.7 ×1
python-2.x ×1
replace ×1
selenium ×1
syntax-error ×1
unicode ×1
utf ×1
utf-8 ×1