请帮我写下txt文件松弛消息历史记录并在其中查找常用字词。 在我的代码示例中,我遇到了问题: 1)只有第一条消息写入文件中。 2)计数器适用于每条消息而不是所有消息历史记录。
from slackclient import SlackClient
from collections import Counter
import re
sc = SlackClient('token')
channel = "C200SFJNR"
def history():
history_call = sc.api_call("channels.history", channel=channel, count=1000)
if history_call.get('ok'):
return history_call['messages']
return None
history = history()
for c in history:
text=(c['text'])
with open("out.txt", 'w') as f:
f.write(text)
words = re.findall(r'\w+', text)
common = Counter(words).most_common(10)
print(common)
答案 0 :(得分:1)
在不了解slackclient的情况下,您的第二个问题很容易回答。您对Counter的引用是循环的。因此,每次引用它时,都会创建一个新实例,旧实例将丢失。你想要的是在你进入循环之前创建一个Counter实例,在循环中向它添加项目然后在你退出循环之后调用most_common来获取那些信息。