使用Python从列表项中删除标点符号

使用Python从列表项中删除标点符号,python,Python,此代码统计唯一和总字数的总数。但是,问题是,如果我写len(uniquewords),它会显示不合理的数字,因为它可以识别例如“shake”“shake!”“摇”和“摇”是不同的独特词汇。 我试图通过制作列表和修改来删除uniquewords中的标点符号,但一切都失败了。有人能帮我吗 使用带有\w+模式的正则表达式匹配单词并排除标点符号 在Python中计数时,使用集合。计数器 此代码的示例数据附加在末尾: from glob import glob pattern = "D:\\report\

此代码统计唯一和总字数的总数。但是,问题是,如果我写len(uniquewords),它会显示不合理的数字,因为它可以识别例如“shake”“shake!”“摇”和“摇”是不同的独特词汇。 我试图通过制作列表和修改来删除uniquewords中的标点符号,但一切都失败了。有人能帮我吗

  • 使用带有
    \w+
    模式的正则表达式匹配单词并排除标点符号
  • 在Python中计数时,使用集合。计数器
  • 此代码的示例数据附加在末尾:

    from glob import glob
    pattern = "D:\\report\\shakeall\\*.txt"
    filelist = glob(pattern)
    def countwords(fp):
        with open(fp) as fh:
            return len(fh.read().split())
    print "There are" ,sum(map(countwords, filelist)), "words in the files. " "From directory",pattern
    import os
    import re
    import string
    uniquewords = set([])
    for root, dirs, files in os.walk("D:\\report\\shakeall"):
        for name in files:
            [uniquewords.add(x) for x in open(os.path.join(root,name)).read().split()]
    wordlist = list(uniquewords)
    
    给出:

    import re
    from collections import Counter
    
    pattern = re.compile(r'\w+')
    
    with open('data') as f:
        text = f.read()
    
    print Counter(pattern.findall(text))
    
    数据:

    finditer(pattern,string,flags=0)返回一个迭代器 针对RE的所有非重叠匹配的MatchObject实例 字符串中的模式。字符串从左到右扫描,并匹配 按找到的顺序返回。空匹配项包含在 结果,除非他们触及另一场比赛的开始。新进 版本2.2


    “文件中的单词”有什么原因吗?“来自目录”不仅仅是“文件中的单词”。来自目录”?在这种情况下,这并不重要,但在一般情况下。您可以逐行读取以保留大文件的内存:
    计数器(f中的逐行逐字读取re.findall(r'\w+',行))
    Counter(
    {'in': 4, 'the': 4, 'string': 3, 'matches': 3, 'are': 2,
    'pattern': 2, '2': 2, 'and': 1, 'all': 1, 'finditer': 1,
    'iterator': 1, 'over': 1, 'an': 1, 'instances': 1,
    'scanned': 1, 'right': 1, 'RE': 1, 'another': 1, 'touch': 1,
    'New': 1, 'to': 1, 'returned': 1, 'Return': 1, 'for': 1,
    '0': 1, 're': 1, 'version': 1, 'Empty': 1, 'is': 1,
    'match': 1, 'non': 1, 'unless': 1, 'overlapping': 1, 'they': 1, 'included': 1, 'The': 1, 'beginning': 1, 'MatchObject': 1,
    'result': 1, 'of': 1, 'yielding': 1, 'flags': 1, 'found': 1,
    'order': 1, 'left': 1})