我有一个来自外部输入源的以下JSON字符串:
{value: "82363549923gnyh49c9djl239pjm01223", id: 17893}
Run Code Online (Sandbox Code Playgroud)
这是错误格式的JSON字符串("id"和"value"必须在引号中),但无论如何我需要解析它.我尝试过simplejson和json-py,似乎无法设置它们来解析这些字符串.
我在Google App引擎上运行Python 2.5,因此任何基于C的解决方案(如python-cjson)都不适用.
输入格式可以更改为XML或YAML,与上面列出的JSON相对应,但我在项目中使用JSON并且在特定位置更改格式不会很好.
现在我已经切换到XML并成功解析数据,但期待任何允许我切换回JSON的解决方案.
我在一台新PC上设置了我的开发环境,看起来我和Fabric有一些奇怪的错误.它的'cd'上下文管理器似乎不会改变当前目录,因此我的很多命令都不起作用.我写了测试,它向我展示了我没想到的结果:
from __future__ import with_statement
from fabric.api import local, run, cd
def xxx():
with cd("src"):
local("pwd")
Run Code Online (Sandbox Code Playgroud)
以下是运行后的结果fab xxx:
[localhost] local: pwd
/home/pioneer/workspace/myproject
Run Code Online (Sandbox Code Playgroud)
但我想,/home/pioneer/workspace/myproject不应该有/home/pioneer/workspace/myproject/src.
我编写了下面的函数,将下划线转换为camelcase,第一个单词为小写,即"get_this_value" - >"getThisValue".此外,我还要求保留前导和尾随下划线以及双重(三重等)下划线,如果有的话,即
"_get__this_value_" -> "_get_ThisValue_".
Run Code Online (Sandbox Code Playgroud)
代码:
def underscore_to_camelcase(value):
output = ""
first_word_passed = False
for word in value.split("_"):
if not word:
output += "_"
continue
if first_word_passed:
output += word.capitalize()
else:
output += word.lower()
first_word_passed = True
return output
Run Code Online (Sandbox Code Playgroud)
我感觉上面的代码是用非Pythonic风格编写的,虽然它按预期工作,所以看看如何简化代码并使用列表推导等编写代码.
我无法通过以下方式将float转换为字符串:
20.02 --> 20.02
20.016 --> 20.02
20.0 --> 20
Run Code Online (Sandbox Code Playgroud)
似乎%g格式是最好的,但我得到奇怪的结果:
In [30]: "%.2g" % 20.03
Out[30]: '20'
In [31]: "%.2g" % 20.1
Out[31]: '20'
In [32]: "%.2g" % 20.3
Out[32]: '20'
In [33]: "%.2g" % 1.2
Out[33]: '1.2'
In [34]: "%.2g" % 1.0
Out[34]: '1'
In [35]: "%.2g" % 2.0
Out[35]: '2'
In [36]: "%.2g" % 2.2
Out[36]: '2.2'
In [37]: "%.2g" % 2.25
Out[37]: '2.2'
In [38]: "%.2g" % 2.26
Out[38]: '2.3'
In [39]: "%.3g" % …Run Code Online (Sandbox Code Playgroud) 我正在尝试遍历列表,我需要在迭代到达列表末尾时执行特定操作,请参阅下面的示例:
data = [1, 2, 3]
data_iter = data.__iter__()
try:
while True:
item = data_iter.next()
try:
do_stuff(item)
break # we just need to do stuff with the first successful item
except:
handle_errors(item) # in case of no success, handle and skip to next item
except StopIteration:
raise Exception("All items weren't successful")
Run Code Online (Sandbox Code Playgroud)
我相信这段代码不是Pythonic,所以我正在寻找更好的方法.我认为理想的代码应该看起来像下面的假设:
data = [1, 2, 3]
for item in data:
try:
do_stuff(item)
break # we just need to do stuff with the first successful item
except:
handle_errors(item) # in …Run Code Online (Sandbox Code Playgroud) 我正在寻找一个正则表达式模式,它可以匹配HTML中没有包装到'a'标签中的URL,以便将它们进一步包装成'a'标签(即突出显示所有非突出显示的链接).
输入是简单的HTML,允许使用'a','b','i','br','p''img'标签.所有其他HTML标记不应出现在输入中,但上面提到的标记可以以任何组合出现.
因此,模式应该省略作为现有"a"标记的一部分的所有网址,并匹配所有其他链接,这些链接只是未包含在"a"标记中的纯文本,因此不会突出显示,也不是超链接.如果模式匹配以http://,https://或www.开头并以.net,.com结尾的网址,那将是一件好事.或.org如果网址不是以http://,https://或www开头.
我试过像'(?!<[aA] [^>] +>)http:// [a-zA-Z0-9 ._-] +(?!)'来匹配比我更简单的情况如上所述,但似乎这个任务并不那么明显.
非常感谢您的帮助.