python - 如何删除每个非字母字符的单词

标签 python python-2.7 python-3.x grammar

我需要编写一个 Python 脚本来删除文本文件中包含非字母字符的每个单词,以测试 Zipf 定律。 例如:

asdf@gmail.com said: I've taken 2 reports to the boss

taken reports to the boss

我应该如何进行?

最佳答案

使用正则表达式只匹配字母(和下划线),你可以这样做:

import re

s = "asdf@gmail.com said: I've taken 2 reports to the boss"
# s = open('text.txt').read()

tokens = s.strip().split()
clean_tokens = [t for t in tokens if re.match(r'[^\W\d]*$', t)]
# ['taken', 'reports', 'to', 'the', 'boss']
clean_s = ' '.join(clean_tokens)
# 'taken reports to the boss'

关于python - 如何删除每个非字母字符的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46486157/

相关文章:

python - 在sympy中获取复杂表达式的系数

python - 根据关联值将值连接到多列中

python - 字典中的 "TypeError: ' unicode ' object does not support item assignment"

python - 部分继承 - 继承一些功能,减去有问题的方法

python - 我需要知道如何让我的函数返回 float 。我对 float 标签的放置位置感到困惑

python - 如何在 csv 列中查找重复项,并删除没有重复项的任何行

python - 在 Robot Framework 中用 Python 登录日志

django - 找出 Django 代码在哪个用户下运行

python - 从现有词典创建频率词典

python - 为什么 python 中的 0.500000 舍入与使用 '%.0f' 的 45.500000 不同?