来自txt文件程序的字数

时间:2014-01-14 06:48:36

标签: python

我正在使用以下代码计算txt文件:

#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
print (word,wordcount)
file.close();

这给了我这样的输出:

>>> 
goat {'goat': 2, 'cow': 1, 'Dog': 1, 'lion': 1, 'snake': 1, 'horse': 1, '': 1, 'tiger': 1, 'cat': 2, 'dog': 1}

但我希望以下列方式输出:

word  wordcount
goat    2
cow     1
dog     1.....

此外,我在输出中获得了一个额外的符号()。我该如何删除?

9 个答案:

答案 0 :(得分:42)

您遇到的有趣符号是UTF-8 BOM (Byte Order Mark)。要摆脱它们,请使用正确的编码打开文件(我假设您使用的是Python 3):

file = open(r"D:\zzzz\names2.txt", "r", encoding="utf-8-sig")

此外,对于计数,您可以使用collections.Counter

from collections import Counter
wordcount = Counter(file.read().split())

显示它们也很简单:

>>> for item in wordcount.items(): print("{}\t{}".format(*item))
...
snake   1
lion    2
goat    2
horse   3

答案 1 :(得分:31)

#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

答案 2 :(得分:1)

import sys
file=open(sys.argv[1],"r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for key in wordcount.keys():
  print ("%s %s " %(key , wordcount[key]))
file.close();

答案 3 :(得分:1)

如果您使用的是graphLab,则可以使用此功能。这真的很强大

products['word_count'] = graphlab.text_analytics.count_words(your_text)

答案 4 :(得分:1)

#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1

for k,v in wordcount.items():
    print k,v
file.close();

答案 5 :(得分:0)

FILE_NAME = 'file.txt'

wordCounter = {}

with open(FILE_NAME,'r') as fh:
  for line in fh:
    # Replacing punctuation characters. Making the string to lower.
    # The split will spit the line into a list.
    word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
    for word in word_list:
      # Adding  the word into the wordCounter dictionary.
      if word not in wordCounter:
        wordCounter[word] = 1
      else:
        # if the word is already in the dictionary update its count.
        wordCounter[word] = wordCounter[word] + 1

print('{:15}{:3}'.format('Word','Count'))
print('-' * 18)

# printing the words and its occurrence.
for  (word,occurance)  in wordCounter.items(): 
  print('{:15}{:3}'.format(word,occurance))
    Word           Count
    ------------------
    of               6
    examples         2
    used             2
    development      2
    modified         2
    open-source      2

答案 6 :(得分:0)

您可以执行以下操作:

file= open(r'D:\\zzzz\\names2.txt')
file_split=set(file.read().split())
print(len(file_split))

答案 7 :(得分:0)

下面来自Python | How to Count the frequency of a word in the text file?的代码对我有用。

 import re
    frequency = {}
    #Open the sample text file in read mode.
    document_text = open('sample.txt', 'r')
    #convert the string of the document in lowercase and assign it to text_string variable.
    text = document_text.read().lower()
    pattern = re.findall(r'\b[a-z]{2,15}\b', text)
    for word in pattern:
         count = frequency.get(word,0)
         frequency[word] = count + 1
     frequency_list = frequency.keys()
     for words in frequency_list:
         print(words, frequency[words])

输出: enter image description here

答案 8 :(得分:-1)

print("sorted counting values:-")
from collections import Counter

fname = open(filename)

fname = fname.read()

fsplit = fname.split()

user  = Counter(fsplit)

for i,v in sorted(user.items()):

   print((v,i))