计算文本fi中的总字数

2024-05-20 02:31:26 发布

您现在位置: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

Tags: nameinforreadifnotitems单词
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类型的构造函数。

您可以通过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']

相关问题 更多 >