计算文本文件中的总字数

时间:2015-02-27 13:57:40

标签: python

我是python的新手,试图打印文本文件中的单词总数以及用户提供的文件中特定单词的总数。

我测试了我的代码,但结果输出了单个单词,但我只需要文件中所有单词的整体字数以及用户提供的单词的总字数。

代码:

name = raw_input("Enter the query x ")
name1 = raw_input("Enter the query y ")
file=open("xmlfil.xml","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

for name in file.read().split():
    if name not in wordcount:
        wordcount[name] = 1
    else:
        wordcount[name] += 1
for k,v in wordcount.items():
    print k, v

for name1 in file.read().split():
    if name1 not in wordcount:
        wordcount[name1] = 1
    else:
        wordcount[name1] += 1
for k,v in wordcount.items():
    print k, v

2 个答案:

答案 0 :(得分:2)

MyFile=open('test.txt','r')
words={}
count=0
given_words=['The','document','1']
for x in MyFile.read().split():
    count+=1
    if x in given_words:
        words.setdefault(x,0)
        words[str(x)]+=1    
MyFile.close()
print count, words

示例输出

  

17 {'1':1,'The':1,'document':1}

请不要将变量命名为处理open()结果file,因为那时您将覆盖file类型的构造函数。

答案 1 :(得分:1)

您可以通过Counter

轻松获得所需内容
from collections import Counter

c = Counter()
with open('your_file', 'rb') as f:
    for ln in f:
        c.update(ln.split())

total = sum(c.values())
specific = c['your_specific_word']