首页 > 解决方案 > python中的语法错误:','后缺少空格

问题描述

在此处输入图像描述有人可以帮我纠正语法错误吗?我在这一行收到语法错误。我不知道为什么会出现语法错误,但是当我检查在线工具是否有 python 错误时,它还指出我有语法错误并且在 ',' 之后缺少空格

下面是代码片段:

d = []  
matches = matcher(doc)
for match_id, start, end in matches:
    rule_id = nlp.vocab.strings[match_id]  # get the unicode ID, i.e. 'COLOR'
    span = doc[start : end]  # get the matched slice of the doc
    d.append((rule_id, span.text))      
keywords = "\n".join(f'{i[0]} {i[1]} ({j})' for i,j in Counter(d).items())

我在这一行收到语法错误:

keywords = "\n".join(f'{i[0]} {i[1]} ({j})' for i,j in Counter(d).items())

SyntaxError:无效的语法

标签: pythonpython-3.xsyntax-error

解决方案


您使用的f-string 语法是在 Python 3.6 中引入的。您要么必须升级 Python 版本,要么使用不同的字符串格式化技术。

一种替代str.format()方法是:

keywords = "\n".join('{} {} ({})'.format(i[0], i[1], j) for i,j in Counter(d).items())

还有旧的 printf 样式格式化方法:

keywords = "\n".join('%s %s (%s)' % (i[0], i[1], j) for i,j in Counter(d).items())

推荐阅读