【发布时间】:2018-05-24 06:11:52
【问题描述】:
使用具有以下内容的虚拟文件 (streamt.txt):
andrew I hate mondays.
fred Python is cool.
fred Ko Ko Bop Ko Ko Bop Ko Ko Bop for ever
andrew @fred no it isn't, what do you think @john???
judy @fred enough with the k-pop
judy RT @fred Python is cool.
andrew RT @judy @fred enough with the k pop
george RT @fred Python is cool.
andrew DM @john Oops
john DM @andrew Who are you go away! Do you know him, @judy?
每行的第一个单词代表一个用户,其余的行是一条消息,类似于 twitter。我需要在他们发送的消息数量旁边打印一个列表,列出前 n 个(由用户输入)原始发帖用户(大多数消息)。
这不包括任何以“RT”开头的消息。在平局的情况下,按字典顺序在对齐的列中格式化。
就目前而言,我的代码仅查找消息中最常用的单词,并且不排除 RT 和 DM 消息或占 n:
file=open('streamt.txt')
counts=dict()
for line in file:
words=line.split()
for word in words:
counts[word]=counts.get(word, 0)+1
lst=list()
for key,value in counts.items():
new=(value, key)
lst.append(new)
lst=sorted (lst, reverse=True)
for value, key in lst[:10]:
print(value,key)
这是我的输出:
6 Ko
5 @fred
4 andrew
3 you
3 is
3 cool.
3 RT
3 Python
3 Bop
2 with
实际输出应该是:
Enter n: 10
3 andrew
2 fred
1 john judy
关于我应该如何做到这一点的任何想法?
【问题讨论】:
-
您的文本文件是否与您的实际输出一致? andrew 不应该按照您的指示为 2 吗?
-
是的,我之前注意到了。那是我得到的输出解决方案,但我想它实际上应该是 2
-
你得到的输出解决方案?看来您甚至没有检查输出是否与说明匹配。
-
原来只有 RT 需要排除
标签: python string file dictionary count