首页 > 解决方案 > Python使用正则表达式将文本拆分为标记

问题描述

嗨,我有一个关于将字符串拆分为标记的问题。

这是一个示例字符串:

string=“就在我等的时候,一个男人从偏房里走出来,一看就知道一定是大个子约翰。他的左腿在臀部附近被割断,左肩下拄着拐杖,他非常灵巧地做到了这一点,像一只鸟一样在上面跳来跳去。他又高又壮,有一张像火腿一样大的脸——朴实而苍白,但聪明而微笑。的确,他看起来精神非常愉快,他一边吹着口哨,一边在桌子之间走动,为他更喜欢的客人说一句快活的话或拍拍肩膀。”

我正在尝试string正确拆分为它的令牌。

这是我的功能count_words

def count_words(text):
    """Count how many times each unique word occurs in text."""
    counts = dict()  # dictionary of { <word>: <count> } pairs to return
    #counts["I"] = 1
    print(text)
    # TODO: Convert to lowercase
    lowerText = text.lower()
    # TODO: Split text into tokens (words), leaving out punctuation
    # (Hint: Use regex to split on non-alphanumeric characters)
    split = re.split("[\s.,!?:;'\"-]+",lowerText)
    print(split)
    # TODO: Aggregate word counts using a dictionary

split这里的结果

['as', 'i', 'was', 'waiting', 'a', 'man', 'come', 'out', 'of', 'a', 'side', 'room', ' and'、'at'、'a'、'glance'、'i'、'was'、'sure'、'he'、'must'、'be'、'long'、'john'、'his' , 'left', 'leg', 'was', 'cut', 'off', 'close', 'by', 'the', 'hip', 'and', 'under', 'the', ' left', 'should', 'he', 'carried', 'a', '拐杖', 'which', 'he', 'managed', 'with', 'wonderful', '灵巧', 'hopping' , '关于', '根据', '它', '喜欢','a','鸟','he','was','very','tall','and','strong','with','a','face','as','big '、'as'、'a'、'ham-plain'、'and'、'pale'、'but'、'intelligent'、'and'、'smiling'、'indeed'、'he'、'似乎', 'in', 'the', 'most', 'cheerful', 'spirits', 'whistle', 'as', 'he', 'moved', 'about', 'among', 'the', 'tables', 'with', 'a', 'merry', 'word', 'or', 'a', 'slap', 'on', 'the', 'should', 'for', 'the '、'更多'、'偏爱'、'的', '他的', '客人', '']

''如您所见,列表的最后一个索引中有空字符串split

请帮助我理解列表中的这个空字符串并正确拆分此示例string

标签: pythonregex

解决方案


您可以使用列表推导来迭代由生成的列表项,re.split并且仅在它们不是空字符串时才保留它们:

def count_words(text):
    """Count how many times each unique word occurs in text."""
    counts = dict()  # dictionary of { <word>: <count> } pairs to return
    #counts["I"] = 1
    print(text)
    # TODO: Convert to lowercase
    lowerText = text.lower()
    # TODO: Split text into tokens (words), leaving out punctuation 
    # (Hint: Use regex to split on non-alphanumeric characters) 

    split = re.split("[\s.,!?:;'\"-]+",lowerText)
    split = [x for x in split if x != '']  # <- list comprehension
    print(split) 

您还应该考虑从函数返回数据,并从调用者打印它,而不是从函数内部打印它。这将为您提供未来的灵活性。


推荐阅读