![](/img/trans.png)
[英]Creating a program which counts words number in a row of a text file (Python)
[英]A program that opens a text file, counts the number of words and reports the top N words ordered by the number of times they appear in the file?
大家好,我是编程的初学者,我最近得到了创建这个程序的任务,我发现很难。 我以前设计过一个程序来计算用户输入的句子中的单词数,是否可以修改这个程序来实现我想要的?
import string
def main():
print "This program calculates the number of words in a sentence"
print
p = raw_input("Enter a sentence: ")
words = string.split(p)
wordCount = len(words)
print "The total word count is:", wordCount
main()
使用collections.Counter
计算单词,使用open()打开文件:
from collections import Counter
def main():
#use open() for opening file.
#Always use `with` statement as it'll automatically close the file for you.
with open(r'C:\Data\test.txt') as f:
#create a list of all words fetched from the file using a list comprehension
words = [word for line in f for word in line.split()]
print "The total word count is:", len(words)
#now use collections.Counter
c = Counter(words)
for word, count in c.most_common():
print word, count
main()
collections.Counter
示例:
>>> from collections import Counter
>>> c = Counter('aaaaabbbdddeeegggg')
Counter.most_common根据计数按排序顺序返回单词:
>>> for word, count in c.most_common():
... print word,count
...
a 5
g 4
b 3
e 3
d 3
要打开文件,可以使用open函数
from collections import Counter
with open('input.txt', 'r') as f:
p = f.read() # p contains contents of entire file
# logic to compute word counts follows here...
words = p.split()
wordCount = len(words)
print "The total word count is:", wordCount
# you want the top N words, so grab it as input
N = int(raw_input("How many words do you want?"))
c = Counter(words)
for w, count in c.most_common(N):
print w, count
import re
from collections import Counter
with open('file_name.txt') as f:
sentence = f.read()
words = re.findall(r'\w+', sentence)
word_counts = Counter(words)
如果其他人收到输入的错误消息,您可能想尝试这个,
码:
N = int(input("\nHow many words do you want: "))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.