我有一些代码,我认为应该返回 python 语句中不在字符串中的所有部分。但是,我不确定这是否像我希望的那样严格。基本上,它只是找到下一个字符串分隔符并保持“字符串”状态,直到它被同一个分隔符关闭。我为一些我没有想到的奇怪案例所做的事情有什么问题吗?它会以任何方式与python所做的不一致吗?
# String delimiters in order of precedence
string_delims = ["'''",'"""',"'",'"']
# Get non string parts of a statement
def get_non_string(text):
out = ""
state = None
while True:
# not in string
if state == None:
vals = [text.find(s) for s in string_delims]
# None will only be reached if all are -1 (i.e. no substring)
for val,delim in zip(vals+[None], string_delims+[None]):
if val == None:
out += text
return out
if val >= 0:
i = val
state = delim
break
out += text[:i]
text = text[i+len(delim):]
else:
i = text.find(state)
if i < 0:
raise SyntaxError("Symobolic Subsystem: EOL while scanning string literal")
text = text[i+len(delim)]
state = None
示例输入:
get_non_string("hello'''everyone'''!' :)'''")
示例输出:
hello!
最佳答案
Python 可以标记 Python 代码:
import tokenize
import token
import io
import collections
class Token(collections.namedtuple('Token', 'num val start end line')):
@property
def name(self):
return token.tok_name[self.num]
def get_non_string(text):
result = []
for tok in tokenize.generate_tokens(io.BytesIO(text).readline):
tok = Token(*tok)
# print(tok.name, tok.val)
if tok.name != 'STRING':
result.append(tok.val)
return ''.join(result)
print(get_non_string("hello'''everyone'''!' :)'''"))
产量
hello!
繁重的工作由 tokenize.generate_tokens 完成。
关于python - 此代码是否正确识别 python 字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15645914/