Python 2.7 Python词频计数程序
我用python创建了一个简单的单词计数程序,它读取一个文本文件,计算单词频率,并将结果写入另一个文件。问题是,当单词被重复时,程序会写入同一单词的初始计数和最终计数。例如,如果一个单词“hello”重复了3次,则程序在输出中写入3个hello实例,如下所示: 词频计数 你好-1 你好-2 你好-3 代码是:Python 2.7 Python词频计数程序,python-2.7,word-frequency,Python 2.7,Word Frequency,我用python创建了一个简单的单词计数程序,它读取一个文本文件,计算单词频率,并将结果写入另一个文件。问题是,当单词被重复时,程序会写入同一单词的初始计数和最终计数。例如,如果一个单词“hello”重复了3次,则程序在输出中写入3个hello实例,如下所示: 词频计数 你好-1 你好-2 你好-3 代码是: counts ={} for w in words: counts[w] = counts.get(w,0) + 1 outfile.write(w+','+str(counts[w]
counts ={}
for w in words:
counts[w] = counts.get(w,0) + 1
outfile.write(w+','+str(counts[w])+'\n')'
任何帮助都将不胜感激。我对python非常陌生。您是否考虑过先在程序中存储频率计数,然后在最后编写它?这当然比为每个计数重写输出文件要简单。您是否考虑过先将频率计数存储在程序中,然后在最后全部写入?这当然比为每次计数重写输出文件要简单。解决此问题的实际方法是使用
计数器,如下所示:
>>> from collections import Counter
>>> words = ['b','b','the','the','the','c']
>>> Counter(words).most_common()
[('the', 3), ('b', 2), ('c', 1)]
另一种解决方法是使用defaultdict
,其工作原理与上面的计数器类似:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for word in words:
... d[word] += 1
...
>>> d
defaultdict(<type 'int'>, {'the': 3, 'b': 2, 'c': 1})
>>从集合导入defaultdict
>>>d=默认dict(int)
>>>用文字表示:
... d[字]+=1
...
>>>d
defaultdict(,{'the':3,'b':2,'c':1})
无论你如何计算字数,你只能在计算完所有字数后写入文件;否则,您将为每个“计数”写入一次,一旦该单词出现多次,您的输出将加倍
因此,首先收集计数,然后写出它们。解决这一问题的实际方法是使用计数器,如下所示:
>>> from collections import Counter
>>> words = ['b','b','the','the','the','c']
>>> Counter(words).most_common()
[('the', 3), ('b', 2), ('c', 1)]
另一种解决方法是使用defaultdict
,其工作原理与上面的计数器类似:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for word in words:
... d[word] += 1
...
>>> d
defaultdict(<type 'int'>, {'the': 3, 'b': 2, 'c': 1})
>>从集合导入defaultdict
>>>d=默认dict(int)
>>>用文字表示:
... d[字]+=1
...
>>>d
defaultdict(,{'the':3,'b':2,'c':1})
无论你如何计算字数,你只能在计算完所有字数后写入文件;否则,您将为每个“计数”写入一次,一旦该单词出现多次,您的输出将加倍
因此,首先收集计数,然后写出它们。使代码工作的方法:
counts ={}
for w in words:
counts[w] = counts.get(w,0) + 1
for w in counts:
outfile.write(w+','+str(counts[w])+'\n')
但我认为Burhan Khalid建议使用计数器是解决问题的更好方法。使代码工作的方法:
counts ={}
for w in words:
counts[w] = counts.get(w,0) + 1
for w in counts:
outfile.write(w+','+str(counts[w])+'\n')
但我认为伯汉·哈立德建议使用计数器是解决这个问题的更好办法。先计数,然后打印。计数时不要打印。所以把最后一行放在它自己的循环中,循环计数。在这种情况下,我无法提取相关单词:首先计数,然后打印。计数时不要打印。所以把最后一行放在它自己的循环中,循环计数。在这种情况下,我无法提取相关单词: