我开发了一个代码,负责读取txt文件的单词,在我的案例中为“elquijote.txt”,然后使用字典{key:value}来显示出现的单词及其出现次数.
例如,对于带有以下单词的文件“test1.txt”:
hello hello hello good bye bye
我的程序输出是:
hello 3
good 1
bye 2
该程序的另一个选项是,它显示的那些单词看起来比我们通过参数引入的数字的次数更多.
如果在shell中,我们将以下命令“python readingwords.py text.txt 2”,
将显示文件“test1.txt”中包含的单词,其出现次数超过我们输入的数字,在本例中为2
输出:
hello 3
现在我们可以引入常见词的第三个参数,例如确定连词,它们如此通用,我们不希望在字典中显示或引入.
我的代码工作正常,问题是使用大文件,如“elquijote.txt”需要很长时间才能完成整个过程.
我一直在想,这是因为我使用我的辅助列表来消除单词.
我认为作为一种解决方案,不要在我的列表中引入由参数输入的txt文件中出现的单词,其中包含要丢弃的单词.
这是我的代码:
def contar(aux):
counts = {}
for palabra in aux:
palabra = palabra.lower()
if palabra not in counts:
counts[palabra] = 0
counts[palabra] += 1
return counts
def main():
characters = '!?¿-.:;-,><=*»¡'
aux = []
counts = {}
with open(sys.argv[1],'r') as f:
aux = ''.join(c for c in f.read() if c not in characters)
aux = aux.split()
if (len(sys.argv)>3):
with open(sys.argv[3], 'r') as f:
remove = "".join(c for c in f.read())
remove = remove.split()
#Borrar del archivo
for word in aux:
if word in remove:
aux.remove(word)
counts = contar(aux)
for word, count in counts.items():
if count > int(sys.argv[2]):
print word, count
if __name__ == '__main__':
main()
Contar函数引入了字典中的单词.
主函数在“aux”列表中引入那些不包含符号字符的单词,然后从同一列表中删除从另一个.txt文件加载的“禁止”单词.
我认为正确的解决方案是丢弃禁止的词语,我丢弃不被接受的符号,但在尝试了几种方法之后,我还没有成功地做到这一点.