python - 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
。
解决方案
您可以使用列表推导来迭代由生成的列表项,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)
您还应该考虑从函数返回数据,并从调用者打印它,而不是从函数内部打印它。这将为您提供未来的灵活性。
推荐阅读
- java - loadrunner - java 协议无法格式化消息!(消息长度大于5KB)
- docker - 自定义 Nginx conf 未反映在 uwsgi-nginx docker 映像中
- css - 用于角色映射的 Keycloak 管理控制台窗口
- kubernetes - Ngnix 入口控制器 Modsecurity(OWASP 规则集)高延迟响应
- openshift - 我可以在 OpenShift 中存储掌舵图并使用它吗?
- javascript - 在超链接中包装关键字 - 替换发生无数次
- amazon-web-services - 如何启用来自 VPC 流日志的电子邮件警报以进行威胁检测?
- python - 无法重新创建 MariaDB 连接池
- python - 如何应用基本矩阵将 3D 点从相机 1 的世界坐标转换为相机 2 的世界坐标
- sql - 从字符串中获取大写字母