【问题标题】:tokenize according space and punctuation, punctuation kept根据空格和标点符号化,保留标点符号
【发布时间】:2018-01-25 00:14:33
【问题描述】:

我正在寻找一种根据空格或标点符号化或拆分的解决方案。结果中只能保留标点符号。它将用于识别语言(python、java、html、c...)

输入 string 可能是:

class Foldermanagement():
def __init__(self):
    self.today = invoicemng.gettoday()
    ...

我期望的输出是一个列表/标记,如下所述:

['class', 'Foldermanagement', '(', ')', ':', 'def', '_', '_', 'init', ... ,'self', '.', 'today', '=', ...]

欢迎任何解决方案,提前致谢。

【问题讨论】:

  • 在大多数编程语言中,下划线“_”被视为字母字符。您可能不想将其视为标点符号。
  • @DYZ 我会记住这一点,谢谢你的评论。我将相应地修改下面的代码。

标签: python string tokenize


【解决方案1】:

我想这就是你要找的东西:

import string, re, itertools
text = """
class Foldermanagement():
def __init__(self):
    self.today = invoicemng.gettoday()
       """
separators = string.punctuation + string.whitespace
separators_re = "|".join(re.escape(x) for x in separators)
tokens = zip(re.split(separators_re, text), re.findall(separators_re, text))
flattened = itertools.chain.from_iterable(tokens)
cleaned = [x for x in flattened if x and not x.isspace()]
# ['class', 'Foldermanagement', '(', ')', ':', 'def', '_', '_',
#  'init', '_', '_', '(', 'self', ')', ':', 'self', '.', 'today', '=', 
#  'invoicemng', '.', 'gettoday', '(', ')']

【讨论】:

  • 宾果游戏!谢谢你。我真的需要深入了解re 包。
猜你喜欢
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 2019-05-09
  • 2014-06-20
  • 2016-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多