我在处理从不同网页(在不同网站上)获取的文本中的unicode字符时遇到问题.我正在使用BeautifulSoup.
问题是错误并不总是可重现的; 它有时适用于某些页面,有时候,它会通过抛出一个UnicodeEncodeError
.我已经尝试了几乎所有我能想到的东西,但是我没有找到任何可以持续工作的东西而不会抛出某种与Unicode相关的错误.
导致问题的代码部分之一如下所示:
agent_telno = agent.find('div', 'agent_contact_number')
agent_telno = '' if agent_telno is None else agent_telno.contents[0]
p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
Run Code Online (Sandbox Code Playgroud)
以下是运行上述代码段时在SOME字符串上生成的堆栈跟踪:
Traceback (most recent call last):
File "foobar.py", line 792, in <module>
p.agent_info = str(agent_contact + ' ' + agent_telno).strip()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我怀疑这是因为某些页面(或更具体地说,来自某些站点的页面)可能被编码,而其他页面可能是未编码的.所有这些网站都位于英国,并提供供英国消费的数据 - 因此,没有与内部化或处理用英语以外的任何文字处理的文本相关的问题.
有没有人有任何想法如何解决这个问题,以便我可以一致地解决这个问题?
我正在编写一个快速而肮脏的脚本来动态生成绘图.我使用下面的代码(来自Matplotlib文档)作为起点:
from pylab import figure, axes, pie, title, show
# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})
show() # Actually, don't show, just save to foo.png
Run Code Online (Sandbox Code Playgroud)
我不想在GUI上显示绘图,相反,我想将绘图保存到文件(例如foo.png),因此,例如,它可以在批处理脚本中使用.我怎么做?
我刚刚在代码中发现了一个逻辑错误,导致了各种各样的问题.我无意中做了一个按位AND而不是逻辑AND.
我更改了代码:
r = mlab.csv2rec(datafile, delimiter=',', names=COL_HEADERS)
mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[mask]
Run Code Online (Sandbox Code Playgroud)
至:
r = mlab.csv2rec(datafile, delimiter=',', names=COL_HEADERS)
mask = ((r["dt"] >= startdate) and (r["dt"] <= enddate))
selected = r[mask]
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,我收到了相当神秘的错误消息:
ValueError:具有多个元素的数组的真值是不明确的.使用a.any()或a.all()
为什么在使用按位操作时没有发出类似的错误 - 我该如何解决这个问题?
我试图将包含行的文件读入Bash数组.
到目前为止,我已尝试过以下内容:
a=( $( cat /path/to/filename ) )
Run Code Online (Sandbox Code Playgroud)
index=0
while read line ; do
MYARRAY[$index]="$line"
index=$(($index+1))
done < /path/to/filename
Run Code Online (Sandbox Code Playgroud)
两次尝试仅返回包含文件第一行的一个元素数组.我究竟做错了什么?
我正在运行bash 4.1.5
我试图将字典中的数据插入数据库.我想迭代值并相应地格式化它们,具体取决于数据类型.这是我正在使用的代码片段:
def _db_inserts(dbinfo):
try:
rows = dbinfo['datarows']
for row in rows:
field_names = ",".join(["'{0}'".format(x) for x in row.keys()])
value_list = row.values()
for pos, value in enumerate(value_list):
if isinstance(value, str):
value_list[pos] = "'{0}'".format(value)
elif isinstance(value, datetime):
value_list[pos] = "'{0}'".format(value.strftime('%Y-%m-%d'))
values = ",".join(value_list)
sql = "INSERT INTO table_foobar ({0}) VALUES ({1})".format(field_names, values)
except Exception as e:
print 'BARFED with msg:',e
Run Code Online (Sandbox Code Playgroud)
当我使用一些示例数据(见下文)运行算法时,我收到错误:
TypeError:序列项0:期望字符串,找到int
给出上述错误的value_list数据的示例是:
value_list = [377, -99999, -99999, 'f', -99999, -99999, -99999, 1108.0999999999999, 0, 'f', -99999, 0, 'f', -99999, 'f', -99999, 1108.0999999999999, …
Run Code Online (Sandbox Code Playgroud) 我使用手工制作的SQL来使用SqlAlchemy从PG数据库中获取数据.我正在尝试一个包含SQL运算符'%'的查询,并且似乎通过循环抛出SqlAlcjhemy:
sql = """
SELECT DISTINCT u.name from user u
INNER JOIN city c ON u.city_id = c.id
WHERE c.designation=upper('fantasy')
AND c.id IN (select id from ref_geog where short_name LIKE '%opt')
"""
# The last line in the above statement throws the error mentioned in the title.
# However if the last line is change to:
# AND c.id IN (select id from ref_geog where short_name = 'helloopt')
# the script runs correctly.
#
# I also tried double escaping …
Run Code Online (Sandbox Code Playgroud) 我最近来到了bootstrap,我正在努力扩展英雄榜样.我想在页面中添加以下行为:
当单击按钮(即具有选择器'.row .btn'的元素)时,我希望能够在展开/折叠按钮上方的文本部分之间切换.
这就是HTML的样子:
<html>
<head>
<title>Test Page</title>
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 60px;
padding-bottom: 40px;
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
</head>
<body>
<div class="navbar navbar-fixed-top">
</div>
<div class="container">
<div class="hero-unit">
<h1>Hello, world!</h1>
<p>Blah, blah.</p>
<p><a class="btn btn-primary btn-large">Learn more »</a></p>
</div>
<!-- Example row of columns -->
<div class="row">
<div class="span4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, …
Run Code Online (Sandbox Code Playgroud) 我在R中创建一个图,我不喜欢由R绘制的x轴值.
例如:
x <- seq(10,200,10)
y <- runif(x)
plot(x,y)
Run Code Online (Sandbox Code Playgroud)
这绘制了一个在X轴上具有以下值的图形:
50, 100, 150, 200
但是,我想将10,20, 30 ... 200
存储在变量x中的20个值绘制为X轴值.我已经浏览了无数的博客和简洁的手册 - 经过几个小时的搜索,我最接近发现任何有用的东西是以下(摘要)说明:
plot()
或par()
指定参数xaxt='n'
axis()
例如axis(side = 1, at = seq(0, 10, by = 0.1), labels = FALSE, tcl = -0.2)
我尝试了它,结果绘图根本没有x轴值.是否有人可以知道如何做到这一点?我无法相信以前没有人试过这样做过.
我在matplotlib中使用pylab来创建绘图并将绘图保存到图像文件中.但是,当我使用保存图像时pylab.savefig( image_name )
,我发现保存的SIZE图像与我使用时显示的图像相同pylab.show()
.
碰巧,我在绘图中有很多数据,当我使用时pylab.show()
,我必须最大化窗口才能正确看到所有绘图,并且xlabel代码不会相互叠加.
无论如何,我可以在将图像保存到文件之前以编程方式"最大化"窗口吗? - 目前,我只获得'默认'窗口大小的图像,这导致x轴标签相互叠加.
我刚刚使用Cython将我的C库的一部分编译为扩展,作为"概念证明".我设法破解了代码(const纠正问题等),最终得到了一个扩展.
但是,当我尝试导入新创建的扩展时,我收到以下错误:
ImportError: dynamic module does not define init function
Run Code Online (Sandbox Code Playgroud)
我做错了什么,如何解决这个问题?
我在Ubuntu 10.0.4上使用Cythn 0.11.2和Python 2.6.5
python ×7
matplotlib ×2
plot ×2
arrays ×1
bash ×1
css ×1
cython ×1
javascript ×1
jquery ×1
numpy ×1
postgresql ×1
python-2.x ×1
r ×1
sqlalchemy ×1
unicode ×1