如何将文本文件与文本字典进行比较,并为匹配的文本指定特定的颜色?

2024-05-04 08:47:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个keyword_file和一个log_file,我想比较这两个文件并突出显示匹配文本的整行。你知道吗

keywords_file = open('keyword_file')
keywords_dict = {word: 0 for word in keywords_file.readlines().strip().split(' ')} # Iterate through all the words removing '\characters and generate a dict

# Then read the chat log
chat_log_file = open('log_file')
chat_log_words_generator = (word for word in chat_log_file.readlines().strip().split(' ')) # Create a generator with the words from the chat log


for word in chat_log_words_generator:
    try:
        word_count = keywords_dict[word]
    except Key-error:
        continue # The word is not a keyword
    word_count += 1 # increment the total
    keywords_dict[word] = word_count

我从网上得到了上面的代码,但是失败了。我收到的错误信息是:

is...
Trace back (most recent call last):
  File "main.py", line 2, in <module>
    keywords_file = open('keyword_file')
FileNotFoundError: [Err-no 2] No such file or directory: 'keyword_file

Tags: theinlogforcountchatopengenerator
1条回答
网友
1楼 · 发布于 2024-05-04 08:47:02

比较日志文件和关键字文件,并突出显示控制台上匹配的文本

代码:

import os

dir_path = 'M:/Desktop/Python-Test/'
keyword_file = os.path.join(dir_path, 'keyword_file.txt')
log_file = os.path.join(dir_path, 'log_file.txt')

with open(keyword_file, 'r') as file1:
    with open(log_file, 'r') as file2:
        file1_txt = file1.read().strip().split()
        file2_txt = file2.read().strip().split()
        gen_list = ['\033[1;37;40m{}'.format(word) if word in file1_txt else '\033[0;0m{}'.format(word) for word in file2_txt]

gen_str = '\033[0;0m '.join(gen_list)  
print(gen_str)

相关问题 更多 >