6

こんにちは、プログラミングの初心者です。最近、このプログラムを作成するタスクを与えられましたが、難しいと感じています。ユーザーが入力した文の単語数を計算するプログラムを以前に設計しましたが、このプログラムを変更して目的を達成することは可能ですか?

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()
4

4 に答える 4

7

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
于 2013-07-05T16:45:00.657 に答える
1

ファイルを開くには、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
于 2013-07-05T16:49:55.413 に答える
0
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)
于 2013-07-05T16:50:59.250 に答える