2012-08-11 3 views
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)을 쓰면, 예를 들어 '쉐이크' '쉐이크'를 인식하기 때문에 불합리한 수를 보여줍니다. '흔들어 라!'하고 '흔들어 라?' 다른 고유 한 단어로. 목록을 만들고 수정하여 모든 유니크 워드에서 구두점을 제거하려고 시도했습니다. 모든 것이 실패했습니다. 아무도 나를 도울 수 있습니까? \w+ 패턴파이썬을 사용하여 목록 항목에서 구두점 제거하기

+0

[SO에 코드를 형식하는 방법] (http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks) – Levon

+0

' 파일에서 단어 ""디렉토리에서 "단순히 파일의 단어가 아닙니다." "디렉토리에서? – Levon

+1

http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python –

답변

1
  1. 사용 정규식은 단어를 일치와 문장을 제외합니다.
  2. 이 코드 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.fin diter (pattern, string, flags = 0) 문자열의 RE 패턴에 대해 겹치지 않는 모든 일치에 대해 MatchObject 인스턴스를 생성하는 반복자를 반환합니다. 문자열이 왼쪽에서 오른쪽으로 스캔되고 일치하는 이 발견 된 순서대로 반환됩니다. 빈 일치 항목은 다른 일치 항목의 시작 부분을 터치하지 않는 한 결과에 포함됩니다. 버전 2.2의 새로운 기능입니다.

+0

이 경우에는 문제가되지 않지만 일반적으로 [카운터는 느린 옵션입니다] (http://stackoverflow.com/a/2525617/4279). 대용량 파일의 메모리를 보존하기 위해 줄 단위로 읽을 수 있습니다 :'Counter (re.findall (r '\ w +', line)에있는 단어의 f에있는 단어)' – jfs

관련 문제