简体   繁体   English

如何在Python 2.7中使用raw_input捕获EOFError上的值?

[英]How to capture the value on EOFError with raw_input in Python 2.7?

raw data: 原始数据:

k = {u'description': u'First Contentful Paint marks the time at which the first text or image is painted. [Learn more].', u'title': u'First Contentful Paint', u'score': 1.0, u'scoreDisplayMode': u'numeric', u'displayValue': u'0.5\xa0s', u'id': u'first-contentful-paint'}

snippet: 片段:

data = k["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"]

try:
    val = raw_input(data.encode("utf-8"))
except EOFError:
    print("skipped")

print "output: " + val

In the above snippet, how can I store the results in val ; 在以上代码段中,如何将结果存储在val the step is skipped when there is a EOFError on line val = raw_input(data.encode("utf-8")) val = raw_input(data.encode("utf-8"))行上出现EOFError时,将跳过该步骤

Here is the actual output I get, and I am unable to store the values xx s in a variable 这是我得到的实际输出,我无法将值xx s存储在变量中

0.5 sskipped

output: 

Expected: 预期:

output: 0.5s

Python version: 2.7 Python版本: 2.7

One way to decode '0.5\\xa0s' is to use unicode builtin function to convert this to unicode and tell it to ignore non utf-8 characters, and convert it to string 解码'0.5\\xa0s'一种方法是使用unicode内置函数将其转换为unicode,并告诉其忽略非utf-8字符,然后将其转换为字符串

>>> a = '0.5\xa0s'
>>> str(unicode(a, errors='ignore'))
'0.5s'

As Devesh explained, I ignored the errors to get rid of the issue that I was facing. 正如Devesh解释的那样,我忽略了这些错误以摆脱所面临的问题。

>>> a = '0.5\xa0s'
>>> a.encode(encoding="ascii", errors="ignore")
'0.5s'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM