第一篇帖子请好心的,我已经搜索了很多,但我找到的大部分内容都与Python 2有关.
我有一个Python3脚本,可以从文件列表中构建一个zip文件; 仅当脚本从crontab运行时,它才会失败并显示UnicodeEncodeError,但是当它从交互式控制台运行时它可以正常运行.我想环境中一定有东西,但我似乎无法弄清楚是什么.
这是代码摘录:
def zipFileList(self, rootfolder, filelist, zip_file, logger):
count = 0
logger.info("Generazione file zip {0}: da {1} files".format(zip_file, len(filelist)))
zip = zipfile.ZipFile(zip_file, "w", compression=zipfile.ZIP_DEFLATED)
for curfile in filelist:
zip.write(os.path.join(rootfolder, curfile), curfile, zipfile.ZIP_DEFLATED)
count = count + 1
zip.close()
logger.info("Scrittura terminata: {0} files".format(count))
Run Code Online (Sandbox Code Playgroud)
这是此代码片段的日志输出:
2012-07-31 09:10:03,033: root - ERROR - Traceback (most recent call last):
File "/usr/local/lib/python3.2/zipfile.py", line 365, in _encodeFilenameFlags
return self.filename.encode('ascii'), self.flag_bits
UnicodeEncodeError: 'ascii' codec can't encode characters in position 56-57: ordinal not in range(128)
During …Run Code Online (Sandbox Code Playgroud) 我试图打印unicode字符给他们的名字如下:
# -*- coding: utf-8 -*-
print "\N{SOLIDUS}"
print "\N{BLACK SPADE SUIT}"
Run Code Online (Sandbox Code Playgroud)
然而,我得到的输出并不是很令人鼓舞.
转义序列按原样打印.
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on
Type "help", "copyright", "credits" or "license" for more information.
>>> # -*- coding: utf-8 -*-
... print "\N{SOLIDUS}"
\N{SOLIDUS}
>>> print "\N{BLACK SPADE SUIT}"
\N{BLACK SPADE SUIT}
>>>
Run Code Online (Sandbox Code Playgroud)
然而,我可以看到另一个提问者已经能够成功地做到这一点.
怎么了?
大家早上好,
我有一个pandas包含多个系列的数据框.对于数据框中的给定系列,数据类型为unicode,NaN和int/float.我想确定系列中的NaN数量但不能使用内置numpy.isnan方法,因为它无法安全地将unicode数据转换为它可以解释的格式.我提出了一个解决方案,但我想知道是否有更好/更多的Pythonic方法来完成这项任务.
提前谢谢,迈尔斯
import pandas as pd
import numpy as np
test = pd.Series(data = [NaN, 2, u'string'])
np.isnan(test).sum()
#Error
#Work around
test2 = [x for x in test if not(isinstance(x, unicode))]
numNaNs = np.isnan(test2).sum()
Run Code Online (Sandbox Code Playgroud) 我刚刚遇到一个正在运行的应用程序的一些unicode错误,每次都要处理非常奇怪的字符串,最近,
P?nar Kars?yaka
Run Code Online (Sandbox Code Playgroud)
在我的开发环境中(Aptana w.PyDev on Mavericks Mac上有一个最新的自制软件安装),处理这个字符串不会产生错误,并打印到控制台
P\u0131nar Kars\u0131yaka v Torku Selcuk
Run Code Online (Sandbox Code Playgroud)
但是在生产环境中,标准的Ubuntu和Python安装在Amazon EC2小盒子上,打印得像
P\xc4\xb1nar Kars\xc4\xb1yaka v Torku Selcuk
Run Code Online (Sandbox Code Playgroud)
并给出一个可怕的Python错误,
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0131' in position 50: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我想知道如何(如果可能的话)使prod环境能够处理这些字符,比如我的开发环境可以,但也希望能够改变我的开发环境,像prod一样打破,所以我可以处理代码中发生这种情况的事件.
感谢您对此提供任何帮助.
Mac Python - Python 2.7.5(默认,2013年11月1日,18:38:34)[GCC 4.2.1兼容的Apple LLVM 5.0(clang-500.2.79)]在达尔文
Ubuntu Python - Python 2.7.3(默认,2013年4月10日,06:20:15)[gCC 4.6.3]在linux2上
python development-environment production-environment python-unicode
我使用 Pytesseract 对屏幕截图运行大量 OCR。这在大多数情况下运行良好,但少数情况会导致此错误:
pytesseract.image_to_string(image,None, False, "-psm 6")
Pytesseract: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
我正在使用Python 3.4。任何如何防止此错误发生的建议(不仅仅是尝试/例外)都会非常有帮助。
如何textwrap在行达到一定字节数之前使用模块拆分(不拆分多字节字符)?
我想要这样的东西:
>>> textwrap.wrap('? ?? ?? ? ? ?? ??', bytewidth=10)
? ??
?? ?
? ??
??
Run Code Online (Sandbox Code Playgroud) keyAWS S3通知事件中表示文件名的字段是URL转义的.
当文件名包含空格或非ASCII字符时,这很明显.
例如,我已将以下文件名上传到S3:
my file ??????.txt
Run Code Online (Sandbox Code Playgroud)
通知收到:
{
"Records": [
"s3": {
"object": {
"key": u"my+file+%C5%99%C4%9B%C4%85%CE%BB%CE%BB%CF%85.txt"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我试过解码使用:
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
但是产量:
my file ÅÄÄλλÏ.txt
Run Code Online (Sandbox Code Playgroud)
当然,当我尝试使用Boto从S3获取文件时,我收到404错误.
我在json文件中有一个1500表情符号字符列表,我想将它们导入我的python代码,我做了一个文件读取并将其转换为python字典,但现在我只有143条记录.如何将所有表情符号导入我的代码,这是我的代码.
import sys
import ast
file = open('emojidescription.json','r').read()
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
emoji_dictionary = ast.literal_eval(file.translate(non_bmp_map))
#word = word.replaceAll(",", " ");
keys = list(emoji_dictionary["emojis"][0].keys())
values = list(emoji_dictionary["emojis"][0].values())
file_write = open('output.txt','a')
print(len(keys))
for i in range(len(keys)):
try:
content = 'word = word.replace("{0}", "{1}")'.format(keys[i],values[i][0])
except Exception as e:
content = 'word = word.replace("{0}", "{1}")'.format(keys[i],'')
#file.write()
#print(keys[i],values[i])
print(content)
file_write.close()
Run Code Online (Sandbox Code Playgroud)
这是我的输入样本
{
"emojis": [
{
"?": ["Graduate"],
"©": ["Copy right"],
"®": ["Registered"],
"??": ["family"],
"?????": ["love"],
"™": ["trademark"],
"???": ["love"],
"?": ["time"], …Run Code Online (Sandbox Code Playgroud) 我正在尝试导入文本文件并将其保存在桌面上,但是文本位于“ utf-8”中(书中有此信息),因此,当我保存而不进行编码时,会有很多奇怪的字符,但是当我尝试使用显式编码保存此错误出现:
Run Code Online (Sandbox Code Playgroud)Traceback (most recent call last): File "C:/Users/Unidas/Semestre/ABC/8.1.py", line 14, in n_palabras libro.write(archivo.read()) TypeError: write() argument 1 must be unicode, not str
代码:
def n_palabras(x):
import urllib2
import io
import string
archivo = urllib2.urlopen(x)
libro = io.open("alice.txt", "w", encoding="utf8")
libro.write(archivo.read())
libro.close()
Run Code Online (Sandbox Code Playgroud)
如何使用utf-8编码保存此文件?我在Python 2.7中使用Pycharm
我正在尝试收集波斯语推文并进行文本分析。我用 tweepy 来做到这一点。但结果是unicode格式。如何将 unicode 文本转换为真正的波斯语文本?
\n\n import tweepy\n import csv\n import pandas as pd\n ####input your credentials here\n consumer_key = xxxx\n consumer_secret = xxxx\n access_token = xxxx\n access_token_secret = xxxx\n\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth,wait_on_rate_limit=True)\n #####United Airlines\n # Open/Create a file to append data\n csvFile = open(\'got5.txt\', \'a\')\n #Use csv Writer\n csvWriter = csv.writer(csvFile)\n\n for tweet in tweepy.Cursor(api.search,q="\xda\xaf\xd8\xa7\xd8\xaa", count=5,\n lang="fa",\n since="2017-04-03").items():\ncsvWriter.writerow([tweet.created_at, tweet.text.encode(\'utf-8\')])\nprint([tweet.created_at, tweet.text.encode(\'utf-8\')])\nRun Code Online (Sandbox Code Playgroud)\n\n结果:
\n\n 2019-07-11 17:09:17,b\'@StingTIcon \\xd8\\xa8\\xd8\\xa7\\xd8\\xb2 \\xd8\\xa7\\xdb\\x8c\\xd9\\x86 \\xd8\\xae\\xd9\\x88\\xd8\\xa8\\xd9\\x87 =)))))) \\xd8\\xa7\\xd9\\x88\\xd9\\x86\\xd8\\xa7\\xdb\\x8c\\xdb\\x8c \\xda\\xa9\\xd9\\x87 \\xd9\\x85\\xdb\\x8c\\xda\\xaf\\xd9\\x85 \\xd8\\xaa\\xd8\\xa7\\xd8\\xa8\\xd9\\x84\\xd9\\x88\\xd8\\xaa\\xd8\\xb1\\xdb\\x8c\\xd9\\x86 …Run Code Online (Sandbox Code Playgroud) python-unicode ×10
python ×8
python-2.7 ×3
python-3.x ×3
unicode ×2
amazon-s3 ×1
aws-lambda ×1
emoji ×1
nan ×1
numpy ×1
pandas ×1
split ×1
tesseract ×1
tweepy ×1
urllib2 ×1
utf-8 ×1
word-wrap ×1