我正在尝试编写一个程序来提取用户输入的代码中的注释.我试图使用正则表达式,但发现很难写.
然后我在这里找到了一个帖子.答案建议用来tokenize.generate_tokens分析语法,但文档说:
所述
generate_tokens()发电机需要一个参数,readline,它必须是一个可调用的对象,它提供了相同的接口readline()的方法内置的文件对象(见文件对象).
但是字符串对象没有readline方法.
然后我在这里发现了另一篇文章,建议StringIO.StringIO用来获取readline方法.所以我写了下面的代码:
import tokenize
import io
import StringIO
def extract(code):
res = []
comment = None
stringio = StringIO.StringIO(code)
for toktype, tokval, begin, end, line in tokenize.generate_tokens(stringio):
# print(toknum,tokval)
if toktype != tokenize.COMMENT:
res.append((toktype, tokval))
else:
print tokenize.untokenize(toktype)
return tokenize.untokenize(res)
Run Code Online (Sandbox Code Playgroud)
并输入以下代码: extract('a = 1+2#A Comment')
但得到了:
Traceback (most recent call last):
File "<stdin>", line 1, in <module> …Run Code Online (Sandbox Code Playgroud) 有没有办法在文字字符串列表中的错过逗号上获取lint错误?
例:
exceptions = ["banana", "pineapple", "apple"
"pen"]
Run Code Online (Sandbox Code Playgroud)
您可能认为此列表包含4个项目,但事实是要说明!"apple"和"pen"加入"applepen".
我害怕这些省略的逗号.有没有一些lint工具可以帮我找到它们?
例2:
exceptions = ["Carmichael",
"Vanessa" # <--- Spot the missing comma
"Ford"]
Run Code Online (Sandbox Code Playgroud) 我一直在尝试创建一个简单的字典来定义用户输入的单词.在定义字典及其单词后,我正在尝试打印输入单词的定义.出于某种原因,当我尝试运行此程序时,列表中的冒号出现语法错误.我不知道如何解决这个问题,我知道有更简单的方法可以做到这一点,但我正在尝试使用列表.这是迄今为止的代码:
dic1 = [
'bug':'A broken piece of code that causes a program to stop functioning'
'string':'A piece of text'
'integer':'A whole number'
'float':'A decimal number'
'function':'A block of organized and clean code that performs a task/action'
'syntax':'A set of rules that says how a program will be coded'
]
q = input("What coding related word do you want defined?")
if q in dic1:
print(dic1[q])
Run Code Online (Sandbox Code Playgroud) 这是我的代码:
import web
import json
urls = (
'/', 'index'
'/runs', 'runs'
)
app = web.application(urls, globals())
class index:
def GET(self):
render = web.template.render('templates/')
return render.index()
class runs:
def GET(self):
return "Test"
if __name__ == "__main__": app.run()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/web/application.py", line 239, in process
return self.handle()
File "/usr/local/lib/python2.7/dist-packages/web/application.py", line 230, in handle
return self._delegate(fn, self.fvars, args)
File "/usr/local/lib/python2.7/dist-packages/web/application.py", line 419, in _delegate
cls = fvars[f]
KeyError: u'index/runs'
Run Code Online (Sandbox Code Playgroud)
大多数人似乎忘记实际创建类(在我的情况下运行)或如果需要导入它失败.除了检查这些东西,我没有找到任何其他解决方案.