我是Python的新手,正在开发一个程序,用于计算简单文本文件中单词的实例。程序和文本文件将从命令行中读取,因此我已将其包含在我的编程语法中以检查命令行参数。代码在
之下import sys
count={}
with open(sys.argv[1],'r') as f:
for line in f:
for word in line.split():
if word not in count:
count[word] = 1
else:
count[word] += 1
print(word,count[word])
file.close()
count是一个字典,用于存储单词及其出现次数。我希望能够打印出每个单词及其出现的次数,从大多数事件开始到最少出现。
我想知道我是否在正确的轨道上,以及我是否正确使用了系统。谢谢!!
答案 0 :(得分:3)
你做的对我来说很好,人们也可以使用collections.Counter(假设你是python 2.7或更新版本)来获取更多信息,比如每个单词的数量。我的解决方案看起来像这样,可能会有一些改进。
import sys
from collections import Counter
lines = open(sys.argv[1], 'r').readlines()
c = Counter()
for line in lines:
for work in line.strip().split():
c.update(work)
for ind in c:
print ind, c[ind]
答案 1 :(得分:0)
您的最终print
没有循环,因此它只会打印您读取的最后一个单词的计数,该单词仍然是word
的值。
此外,使用with
上下文管理器,您不需要close()
文件句柄。
最后,正如评论中所指出的,您需要在line
之前删除每个split
的最终换行符。
对于像这样的简单程序,它可能不值得麻烦,但您可能希望从defaultdict
查看Collections
以避免在字典中初始化新密钥的特殊情况。 / p>
答案 2 :(得分:0)
我刚注意到一个拼写错误:您将文件打开为f
,但您将其关闭为file
。正如tripleee所说,您不应该关闭在with
语句中打开的文件。此外,使用内置函数的名称(例如file
或list
)作为您自己的标识符也是不好的做法。有时它有效,但有时它会导致讨厌的错误。对于阅读代码的人来说,这让人感到困惑;语法高亮编辑器可以帮助避免这个小问题。
要按照计数的降序打印count
dict中的数据,您可以执行以下操作:
items = count.items()
items.sort(key=lambda (k,v): v, reverse=True)
print '\n'.join('%s: %d' % (k, v) for k,v in items)
有关list.sort()方法和其他方便的dict方法的更多详细信息,请参阅Python Library Reference。
答案 3 :(得分:0)
我刚刚使用re库做到了这一点。这是针对每行文本文件中的平均单词,但您必须找出每行的单词数。
import re
#this program get the average number of words per line
def main():
try:
#get name of file
filename=input('Enter a filename:')
#open the file
infile=open(filename,'r')
#read file contents
contents=infile.read()
line = len(re.findall(r'\n', contents))
count = len(re.findall(r'\w+', contents))
average = count // line
#display fie contents
print(contents)
print('there is an average of', average, 'words per sentence')
#closse the file
infile.close()
except IOError:
print('An error oocurred when trying to read ')
print('the file',filename )
#call main
main()