计算字符串中字典中的键的出现次数

问题描述 投票:0回答:1

我有一个程序可以打开 FTP 服务器上的日志文件并每 1 秒读取一次。如果出现新日志,则会将其插入到 tkinter 文本小部件中。这里还有 color.txt 文本文件,看起来像这样:

abc=green
def=yellow
ghi=blue

功能:

def readdata(text,dir,logfile,title,stop_event):
    scroll.config(command=t.yview)
    global sftp
    cnopts = pysftp.CnOpts()
    cnopts.hostkeys = None
    sftp = pysftp.Connection('ip', username='user', password='pass', cnopts=cnopts)
    root.title(title)
    t.insert(tk.END, text+"LOADING\n\n")
    sftp.chdir('logs')
    sftp.chdir(dir)
    active_log = logfile
    with sftp.open(active_log, mode="r") as file:
        old_logs = file.read().decode('ASCII')
        t.insert(tk.END, old_logs)
        t.see(tk.END)
    while not stop_event.is_set():
        with sftp.open(active_log, mode="r") as file:
            new_logs = file.read().decode('ASCII')
        if new_logs != old_logs:
            t.insert(tk.END, new_logs[len(old_logs):])
            state = var1.get()
            if state==1:
                t.see(tk.END)
            old_logs = new_logs
            with open('colors.txt', 'r') as f:
                for line in f.readlines():
                    phrases, colors= line.rstrip("\n").split("=")
                    myObject[phrases] = colors  # myObject = {'abc': 'green', 'def': 'yellow', 'ghi': 'blue'}
            my_list = list(myObject.keys())
            for k in my_list:       # my_list = ['abc', 'def', 'ghi']
                print(new_logs.count(k))
        time.sleep(1)

在上面的函数中,代码仅获取每个键并将其放入列表中,因此: my_list = ['abc', 'def', 'ghi']

我想检查这些单词在日志中出现了多少次(其中有“new_logs”/“old_logs”变量)。然而,我并没有成功,因为我的大多数试验最终都只计算了一个单词,所以它看起来像这样:

abc=1245
def=0
ghi=0

我还尝试了 Collections 中的 Counter() ,但它正在计算每个字母 (??) 的出现次数,而这些字母甚至没有出现在列表中的任何单词中? 为什么它不计算每个键的出现次数,而只计算一个?这里不应该有任何零,因为在日志中这些键出现了很多次。

python dictionary for-loop
1个回答
0
投票

实际上你不应该使用文本文件来完成Python众所周知的工作。 我建议将 color.txt 更改为 python 文件或 yaml 文件。

此外,您正在使用 rsplit(),它仅删除行尾的空格

with open('colors.txt', 'r') as f:
for line in f.readlines():
    phrases, colors = line.strip().split("=")  # Remove Spaces and split at =
    myObject[phrases.strip()] = colors # your actuall seeking phrases as keys and colors as values

phrases.strip() 确保您在文本文件中存储信息的特殊方式与键值构造相匹配

© www.soinside.com 2019 - 2024. All rights reserved.