如何解决 - 错误:在位置0处出现了错误转义字符\u

13

你好,我正在尝试在Jupyter笔记本中使用ipywidgets导出gmap html,但遇到以下错误:- 错误:位置0处的坏转义符\u。

我是编程新手,需要帮助解决导致此错误发生的问题。如果有更简单的方法来导出html文件,我很乐意改变方法。

谢谢


这是代码片段:如果有帮助,我可以添加整个代码。

import pandas as pd
import gmaps
from ipywidgets.embed import embed_minimal_html
from ipywidgets import IntSlider
gmaps.configure(api_key='XXXX')
pd.options.mode.chained_assignment = None  # default='warn'


file2 = '005 lat:long.csv'
state2 = pd.read_csv(file2)
state2 = state2.rename(columns={'Address1': 'address', 'City':'city', 
                                'State':'state', 'Zip': 'zip'})

storenumbs = state2['Store'].str.split('#', expand=True)
state2 = state2.join(storenumbs)
state2 = state2.drop(['Store', 0], axis=1)
state2 = state2.rename(columns={1: 'store_#'})
state2['store_#'] = state2['store_#'].astype(int)

fig = gmaps.figure(center=(42.5, -71.4), map_type='TERRAIN', zoom_level=9.8)
scale = 4
one_layer = (gmaps.symbol_layer(low_points_lat_long, fill_color='red', stroke_color='red', scale= scale))
two_layer = (gmaps.symbol_layer(low_med_points_lat_long, fill_color='red', stroke_color='yellow', scale= scale))
three_layer = (gmaps.symbol_layer(med_high_points_lat_long, fill_color='yellow', stroke_color='green', scale= scale))
four_layer = (gmaps.symbol_layer(high_points_lat_long, fill_color='green', stroke_color='green', scale= scale))


fig.add_layer(one_layer)
fig.add_layer(two_layer)
fig.add_layer(three_layer)
fig.add_layer(four_layer)

fig
embed_minimal_html('export.html', views=[fig]

以下是长格式错误


)

KeyError                                  Traceback (most recent call last)
~/miniconda3/lib/python3.7/sre_parse.py in parse_template(source, pattern)
   1020                 try:
-> 1021                     this = chr(ESCAPES[this][1])
   1022                 except KeyError:

KeyError: '\\u'

During handling of the above exception, another exception occurred:

error                                     Traceback (most recent call last)
<ipython-input-7-c096ac365396> in <module>
     20 
     21 slider = IntSlider(value=40)
---> 22 embed_minimal_html('export.html', views=[slider], title='Widgets export')

~/miniconda3/lib/python3.7/site-packages/ipywidgets/embed.py in embed_minimal_html(fp, views, title, template, **kwargs)
    300     {embed_kwargs}
    301     """
--> 302     snippet = embed_snippet(views, **kwargs)
    303 
    304     values = {

~/miniconda3/lib/python3.7/site-packages/ipywidgets/embed.py in embed_snippet(views, drop_defaults, state, indent, embed_url, requirejs, cors)
    266     widget_views = u'\n'.join(
    267         widget_view_template.format(view_spec=escape_script(json.dumps(view_spec)))
--> 268         for view_spec in data['view_specs']
    269     )
    270 

~/miniconda3/lib/python3.7/site-packages/ipywidgets/embed.py in <genexpr>(.0)
    266     widget_views = u'\n'.join(
    267         widget_view_template.format(view_spec=escape_script(json.dumps(view_spec)))
--> 268         for view_spec in data['view_specs']
    269     )
    270 

~/miniconda3/lib/python3.7/site-packages/ipywidgets/embed.py in escape_script(s)
    239     involving `<` is readable.
    240     """
--> 241     return script_escape_re.sub(r'\u003c\1', s)
    242 
    243 @doc_subst(_doc_snippets)

~/miniconda3/lib/python3.7/re.py in _subx(pattern, template)
    307 def _subx(pattern, template):
    308     # internal: Pattern.sub/subn implementation helper
--> 309     template = _compile_repl(template, pattern)
    310     if not template[0] and len(template[1]) == 1:
    311         # literal replacement

~/miniconda3/lib/python3.7/re.py in _compile_repl(repl, pattern)
    298 def _compile_repl(repl, pattern):
    299     # internal: compile replacement pattern
--> 300     return sre_parse.parse_template(repl, pattern)
    301 
    302 def _expand(pattern, match, template):

~/miniconda3/lib/python3.7/sre_parse.py in parse_template(source, pattern)
   1022                 except KeyError:
   1023                     if c in ASCIILETTERS:
-> 1024                         raise s.error('bad escape %s' % this, len(this))
   1025                 lappend(this)
   1026         else:

error: bad escape \u at position 0 

你能提供一段你正在执行的代码片段吗? - foxyblue
2
我曾经遇到过类似的问题(sre_constants.error: bad escape \p at position 1),解决方法是 import regex 并使用 regex.sub 而不是 re.sub - JorgeAmVF
script_escape_re是什么? - M.Ionut
3个回答

13

这是Python 3.7的错误,也是Python 3.6的问题(但在Python 2.7中没问题)。

如果在re.sub函数中使用原始字符串(以"r"为前缀)作为替换字符串,则会对\u进行转义。例如,r'\u003c\1'类似于'\\u003c\\1':这是一个字符串'\u',后跟'003c'\1

解决方法是编写:

return script_escape_re.sub('\u003c\\1', s)

NOTE: It can be inferred that script_escape_re is a precompiled regular expression pattern object that is defined elsewhere in the code. For instance:

script_escape_re = re.compile(r'<script>(.*?)</script>', re.IGNORECASE)

引用文档

在版本 3.7 中更改:以'\'和ASCII字母组成的repl中的未知转义现在将产生错误。


script_escape_re是什么? - M.Ionut

2

我在尝试转义具有模式\uXXXX的Unicode字符时遇到了类似的问题。让我们看一个包含Unicode字符的字符串:

>>> text = "The \u201c\u3010\u3011\u201d in this template are used to mark the variables"
>>> text
'The “【】” in this template are used to mark the variables'

转义Unicode字符:

>>> text = text.encode('unicode_escape').decode('ascii')
>>> text
'The \\u201c\\u3010\\u3011\\u201d in this template are used to mark the variables'

然后使用re.sub(r'\\u(.){4}', '', text)替换它们:

>>> import re
>>> re.sub(r'\\u(.){4}', '', text)
'The  in this template are used to mark the variables'

0

我在编程过程中遇到了同样的问题。

 [m.start() for m in re.finditer('Valuation Date")', 'dummytext')]

*** sre_constants.error: unbalanced parenthesis at position 15

但是通过使用re.escape方法,问题得到了解决。

[m.start() for m in re.finditer(re.escape('Valuation Date")'), 'dummytext')]

享受吧。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接