是否有(unix)shell脚本以人类可读的形式格式化XML?
基本上,我希望它改变以下内容:
<root><foo a="b">lorem</foo><bar value="ipsum" /></root>
Run Code Online (Sandbox Code Playgroud)
...进入这样的事情:
<root>
<foo a="b">lorem</foo>
<bar value="ipsum" />
</root>
Run Code Online (Sandbox Code Playgroud) 我见过很少的py脚本在脚本的顶部使用它.在什么情况下应该使用它?
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Run Code Online (Sandbox Code Playgroud) 我的python(ver 2.7)脚本运行良好,从本地html文件中获取一些公司名称,但是当涉及到某个特定的国家/地区名称时,它会出现此错误"UnicodeEncodeError:'ascii'compodec无法编码字符"
当这个公司名称出现时特别收到错误
公司名称:KühlfixKälteanlagenIng.GerhardDoczekal&Co.KG
该链接无法处理
Traceback (most recent call last):
File "C:\Python27\Process2.py", line 261, in <module>
flog.write("\nCompany Name: "+str(pCompanyName))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 9: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
错误在这行代码中给出:
if companyAlreadyKnown == 0:
for hit in soup2.findAll("h1"):
print "Company Name: "+hit.text
pCompanyName = hit.text
flog.write("\nCompany Name: "+str(pCompanyName))
companyObj.setCompanyName(pCompanyName)
Run Code Online (Sandbox Code Playgroud) 我有这个代码:
printinfo = title + "\t" + old_vendor_id + "\t" + apple_id + '\n'
# Write file
f.write (printinfo + '\n')
Run Code Online (Sandbox Code Playgroud)
但是我在运行时遇到这个错误:
f.write(printinfo + '\n')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
它正在编写这个:
Identité secrète (Abduction) [VF]
Run Code Online (Sandbox Code Playgroud)
请任何想法,不知道如何解决.
干杯.
更新:这是我的大部分代码,所以你可以看到我在做什么:
def runLookupEdit(self, event):
newpath1 = pathindir + "/"
errorFileOut = newpath1 + "REPORT.csv"
f = open(errorFileOut, 'w')
global old_vendor_id
for old_vendor_id in vendorIdsIn.splitlines():
writeErrorFile = 0
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True) …Run Code Online (Sandbox Code Playgroud) sys.setdefaultencoding('utf-8')在Python 2中存在令人沮丧的设置趋势.任何人都可以列出问题的真实例子吗?论证喜欢it is harmful或it hides bugs听起来不太令人信服.
更新:请注意,这个问题只是关于utf-8,它不是关于改变默认编码"一般情况下".
如果可以,请举一些代码示例.
您能否根据其密钥和工作表ID(gid)生成一个如何下载Google Docs电子表格的Python示例?我不能.
我已经搜索了API的第1版,第2版和第3版.我没有运气,我无法弄清楚他们编译的类似ATOM的API,gdata.docs.service.DocsService._DownloadFile私有方法说我是未经授权的,而且我不想自己写一个完整的Google登录认证系统.由于沮丧,我准备将自己捅到脸上.
我有一些电子表格,我想这样访问它们:
username = 'mygooglelogin@gmail.com'
password = getpass.getpass()
def get_spreadsheet(key, gid=0):
... (help!) ...
for row in get_spreadsheet('5a3c7f7dcee4b4f'):
cell1, cell2, cell3 = row
...
Run Code Online (Sandbox Code Playgroud)
请保存我的脸.
更新1:我尝试了以下,但没有组合Download()或Export()似乎工作.(DocsService 这里的文件)
import gdata.docs.service
import getpass
import os
import tempfile
import csv
def get_csv(file_path):
return csv.reader(file(file_path).readlines())
def get_spreadsheet(key, gid=0):
gd_client = gdata.docs.service.DocsService()
gd_client.email = 'xxxxxxxxx@gmail.com'
gd_client.password = getpass.getpass()
gd_client.ssl = False
gd_client.source = "My Fancy Spreadsheet Downloader"
gd_client.ProgrammaticLogin()
file_path = tempfile.mktemp(suffix='.csv')
uri …Run Code Online (Sandbox Code Playgroud) 我正在尝试将一些字符串写入文件(字符串已由HTML解析器BeautifulSoup提供给我).
我可以使用"print"来显示它们,但是当我使用file.write()时,我收到以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 6: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我怎么解析这个?
我试图找到我们的python脚本崩溃的原因.
主要结构是这样的:
def main()
try:
dostuff
except Exception as ex:
import traceback
tb = traceback.format_exc()
import platform
node = platform.node()
sendMail([DEBUG_EMAIL], "Alarm exception on %s" % node, str(tb), [])
Run Code Online (Sandbox Code Playgroud)
我在主要的错误处理中得到了这个堆栈跟踪,而不是我应该发送的错误电子邮件.
Traceback (most recent call last):
File "/usr/lib/python2.6/logging/__init__.py", line 799, in emit
stream.write(fs % msg.encode("UTF-8"))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 66: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
从我看到所有对logger的写入调用都在try-block中,但由于它没有在我的电子邮件发送异常块中捕获和处理,所以我似乎错过了一些东西.我已经检查过,sendMail函数根本不使用日志记录模块.所以异常不应该源于我的except-block.
我尝试添加
sys.tracebacklimit = 10
Run Code Online (Sandbox Code Playgroud)
在文件的顶部,查看异常发生的位置但不影响任何内容.而现在我已经没有关于如何找到问题所在的想法.
该脚本每小时运行一次,每周只崩溃一次,这使我认为它与输入数据有关,但这只能由dostuff()处理.
更新:
我已经弄清楚为什么我只得到一行堆栈跟踪.在emit()里面我发现了这个.
try:
... doing stuff, something goes boom with encoding...
except UnicodeError: …Run Code Online (Sandbox Code Playgroud) 将带有外来字符(åäö)的数据框加载到Spark中,使用spark.read.csv,encoding='utf-8'并尝试执行简单的show().
>>> df.show()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/spark/python/pyspark/sql/dataframe.py", line 287, in show
print(self._jdf.showString(n, truncate))
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 579: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我认为这可能与Python本身有关但我无法理解这里提到的任何技巧如何在PySpark和show() - 函数的上下文中应用.
我想将各种Python对象的列表连接成一个字符串.对象可以是字面上的任何东西.我想我可以使用以下代码完成此操作:
' '.join([str(x) for x in the_list])
Run Code Online (Sandbox Code Playgroud)
但不幸的是,有时会给我一个UnicodeEncodeError:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 80: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
在这个SO答案中,我发现有人说我需要使用.encode('utf-8'),所以我将代码更改为:
' '.join([x.encode('utf-8') for x in the_list])
Run Code Online (Sandbox Code Playgroud)
但是如果对象不是字符串或unicodes但是例如ints我得到了一个AttributeError: 'int' object has no attribute 'encode'.所以这意味着我需要使用某种if语句来检查它是什么类型以及如何转换它.但是什么时候应该使用.encode('utf-8'),什么时候应该使用str()?
如果我也可以为此做一些oneliner会更好,但我不知道如何?还有其他人知道吗?欢迎所有提示!
python ×9
encoding ×4
unicode ×3
utf-8 ×3
python-2.x ×2
xml ×2
apache-spark ×1
ascii ×1
command-line ×1
google-docs ×1
pyspark ×1
python-2.7 ×1
sys ×1
unix ×1