我做了一个压缩代码,并在10kb的文本文件上进行了测试,测试时间不少于3分钟。不过,我用了一个1MB的文件来测试它,这是我老师布置的评估,它花了半个多小时。和我的同学相比,我的不规则长。可能是我的电脑或代码,但我不知道。有没有人知道如何缩短我的代码速度的技巧或捷径?我的压缩代码如下,如果有任何更快的方法做循环等。请给我一个答复(:
(顺便说一句,我的代码是如何工作的,所以我不是要求更正,只是要求增强或提示,谢谢!)在import re #used to enable functions(loops, etc.) to find patterns in text file
import os #used for anything referring to directories(files)
from collections import Counter #used to keep track on how many times values are added
size1 = os.path.getsize('file.txt') #find the size(in bytes) of your file, INCLUDING SPACES
print('The size of your file is ', size1,)
words = re.findall('\w+', open('file.txt').read())
wordcounts = Counter(words) #turns all words into array, even capitals
common100 = [x for x, it in Counter(words)