如何在Python中从slack中写入txt文件并在消息历史记录中查找常用词?
How to write in txt file and find common words in message history from slack in Python?
请帮我在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)
你的第二个问题在不了解 slackclient 的情况下很容易回答。您对 Counter 的引用处于循环中。因此,每次您引用它时,都会创建一个新实例,而旧实例会丢失。您想要的是在进入循环之前创建一个 Counter 实例,在循环中向其添加项目,然后在退出循环后调用 most_common 以获取该信息。
请帮我在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)
你的第二个问题在不了解 slackclient 的情况下很容易回答。您对 Counter 的引用处于循环中。因此,每次您引用它时,都会创建一个新实例,而旧实例会丢失。您想要的是在进入循环之前创建一个 Counter 实例,在循环中向其添加项目,然后在退出循环后调用 most_common 以获取该信息。