首页 > 解决方案 > Python 在相同的文本文件上返回不同的结果

问题描述

我是编程新手。我正在使用 powershell 从远程服务器的 Windows 安全事件日志中过滤并返回文本文件中的记录。我正在使用 python 脚本来计算用户名在文本中出现的次数。针对原始文本文件运行时,python 打印并清空字典 {}。但是,如果我复制文本文件的内容并将其粘贴到一个新的文本文件中并针对它运行我的 python 脚本,它会返回正确的计数:{'name1': 2, 'name2': 13, 'name3': 1, 'name4': 1, 'name5': 2, 'name6': 2}. 文本文件看起来相同,字符位置也相同。可能是什么问题呢?

电源外壳

Get-WinEvent -LogName "Security" -ComputerName server01 | Where-Object {$_.ID -eq 4663} | where Message -CNotLike "*name1*" | where Message -CNotLike "*name2*" | Format-List -Property * | Out-File "C:\apowershell\winsec\events.txt"

Python

fhand = open('events2.txt')
counts = dict()
for line in fhand:
    if line.startswith('            Account Name:'):
        words = line.split()
        words.remove('Account')
        words.remove('Name:')
        for word in words:
            if word not in counts:
               counts[word] = 1
            else:
               counts[word] += 1
print(counts)

日志记录消息:试图访问一个对象。

      Subject:
        Security ID:        S-1-5-21-495698755-754321212-623647154-4521
        Account Name:       name1
        Account Domain:     companydomain
        Logon ID:       0x8CB9C5024

      Object:
        Object Server:      Security
        Object Type:        File
        Object Name:        e:\share\file.txt
        Handle ID:      0x439c
        Resource Attributes:    S:PAI

      Process Information:
        Process ID:     0x2de8
        Process Name:       C:\Windows\System32\memshell.exe

      Access Request Information:
        Accesses:       Execute/Traverse

        Access Mask:        0x20

标签: pythonpowershellpython-unicode

解决方案


答案在你的问题陈述中。您正在读取在 MS Windows 上创建的文件,该文件使用在(可能)非 Windows 系统上运行的 python 程序。

问题是原始文件的字符编码与您的 python 程序所期望的不匹配。具体来说,原始文件采用 UCS-2(或 UTF-16)编码。如果您在像操作系统这样的 UNIX 上运行您的 python 代码,它可能需要 UTF-8。但这取决于您的语言环境,请查看locale. 谷歌“python utf-16 decode”了解如何处理这个问题。虽然,就个人而言,我并没有试图让你的 python 程序处理 UTF-16,而是试图找到一种方法在 Windows 系统上将内容转换为 UTF-8。


推荐阅读