0
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)

このコードは、一意の単語と合計単語の合計数をカウントします。しかし問題は、 len(uniquewords) と書くと、たとえば「shake」「shake!」などと認識してしまい、無理な数字になってしまうことです。「シェイク」と「シェイク?」別のユニークな言葉として。リストを作成して変更することで、一意の単語から句読点を削除しようとしましたが、すべて失敗しました。誰でも私を助けることができますか?

4

1 に答える 1

1
  1. 正規\w+表現とパターンを使用して単語を照合し、句読点を除外します。
  2. Pythonでカウントする場合collections.Counter

このコードのサンプル データは最後に追加されます。

import re
from collections import Counter

pattern = re.compile(r'\w+')

with open('data') as f:
    text = f.read()

print Counter(pattern.findall(text))

与えます:

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})

データ:

re.finditer(pattern, string, flags=0) string 内の RE パターンの重複しないすべての一致に対して MatchObject インスタンスを生成する反復子を返します。文字列は左から右にスキャンされ、見つかった順序で一致が返されます。空の一致は、別の一致の先頭に触れない限り、結果に含まれます。バージョン 2.2 の新機能。

于 2012-08-11T11:43:17.157 に答える