有没有相当于ruby's StringScanner class的python类?我可以一起破解一些东西,但是如果已经存在,我不想重新发明轮子。python等价于ruby的StringScanner?
2
A
回答
1
看起来像re.split(pattern, string)
的变体。
0
您是否正在Python中寻找正则表达式?检查此链接来自官方的文档:
-1
也许看看内置的模块tokenize。看起来您可以使用StringIO module将字符串传递给它。
9
import re
def s_ident(scanner, token): return token
def s_operator(scanner, token): return "op%s" % token
def s_float(scanner, token): return float(token)
def s_int(scanner, token): return int(token)
scanner = re.Scanner([
(r"[a-zA-Z_]\w*", s_ident),
(r"\d+\.\d*", s_float),
(r"\d+", s_int),
(r"=|\+|-|\*|/", s_operator),
(r"\s+", None),
])
print scanner.scan("sum = 3*foo + 312.50 + bar")
继它看起来就像是在为实验代码/起点为别人留下的discussion。
4
在Python中没有什么和Ruby的StringScanner一模一样。当然,容易把东西在一起:
import re
class Scanner(object):
def __init__(self, s):
self.s = s
self.offset = 0
def eos(self):
return self.offset == len(self.s)
def scan(self, pattern, flags=0):
if isinstance(pattern, basestring):
pattern = re.compile(pattern, flags)
match = pattern.match(self.s, self.offset)
if match is not None:
self.offset = match.end()
return match.group(0)
return None
随着交互使用它的一个例子
>>> s = Scanner("Hello there!")
>>> s.scan(r"\w+")
'Hello'
>>> s.scan(r"\s+")
' '
>>> s.scan(r"\w+")
'there'
>>> s.eos()
False
>>> s.scan(r".*")
'!'
>>> s.eos()
True
>>>
但是,我做我往往只写一次过那些正则表达式的工作并使用组提取所需的字段。或者对于更复杂的事情,我会写一个一次性的标记器,或者寻找PyParsing或PLY来为我标记。我没有看到自己使用类似StringScanner的东西。
0
今天有马克瓦克森一个项目,在Python实现StringScanner:
http://asgaard.co.uk/p/Python-StringScanner
1
https://pypi.python.org/pypi/scanner/
似乎是一种更维护和功能的完整解决方案。但它直接使用oniguruma。
相关问题
- 1. python等价于ruby的__method__?
- 2. Ruby等价于Python的DictWriter?
- 3. python等价于ruby的`map.with_index`?
- 4. python等价于ruby bundler包
- 5. Python等价于Ruby的包函数
- 6. Python中的“require”(Ruby)等价于什么?
- 7. fromCharCode等价于Ruby
- 8. charCodeAt()等价于Ruby
- 9. Python的等价Ruby的'method_missing'
- 10. Ruby的等价的Python setattr()
- 11. Ruby ::等价于Tie :: FIle?
- 12. PL/Ruby等价于MySQL
- 13. Python等价于bwmorph
- 14. Python等价于ignoreboth:erasedups
- 15. python等价于MATLAB的mxCreateDoubleMatrix
- 16. 等价于python“dir”的Java?
- 17. Python等价于Mathematica的ArrayPlot?
- 18. Python等价于Mathematica的“LaguerreL”
- 19. Perl的等价于python exec?
- 20. C#等价于python的struct.pack
- 21. C++等价于Python的doctests?
- 22. python等价于MySQL的IFNULL
- 23. PHP等价于Python的requests.get
- 24. C#等价于Python的os.path.exists()?
- 25. Python的for Ruby的等价物
- 26. Python的等价物Ruby的each_slice(count)
- 27. Python的延续与Ruby的等价物
- 28. Ruby的等价的Python str [3:]
- 29. 是否有“python -i”的ruby等价物?
- 30. Ruby的watchr在Python中等价吗?
有趣,谢谢! – 2009-11-17 21:54:23