【发布时间】:2017-11-03 13:54:54
【问题描述】:
我开发了一个代码,负责读取 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 函数引入字典中的单词。
主函数在“辅助”列表中引入那些不包含符号字符的单词,然后从同一个列表中删除从另一个 .txt 文件加载的那些“禁止”单词。
我认为正确的解决方案是丢弃那些我丢弃不被接受的符号的禁用词,但是在尝试了几种方法后我没有设法正确地做到这一点。
您可以在这里在线测试我的代码: https://repl.it/Nf3S/54 谢谢。
【问题讨论】:
-
为什么不使用 collections.Counter 进行正常的字数统计,然后消除不需要的字词?将慢速代码移动到较小的音量循环中。
-
您有内存问题吗? “elquijote.txt”可能是一个很长的文件。如果是整本书,它有 381.104 个单词,来自 22.939 个不同的单词和超过 200 万个字符。批量处理这本书应该是个好主意。
标签: python dictionary