【问题标题】:Getting TypeError: unsupported operand type(s) for |=: 'str' and 'bool' message when trying to run script获取类型错误:|= 的不支持的操作数类型:尝试运行脚本时出现“str”和“bool”消息
【发布时间】:2018-08-17 12:50:33
【问题描述】:

我有一个 python 脚本,我试图确定 json 格式的 .txt 文件是否返回正数或负数以包含某些语句。一些示例语句是:“高曝光率”、“网络钓鱼和其他欺诈”、“可疑内容”。在确定每个 .txt 文件返回正数还是负数后,脚本应该将结果写入 csv。我正在尝试处理大约 100,000 个 .txt 文件。我得到了我的代码的TypeError on line 22。完整的错误信息是:

TypeError: unsupported operand type(s) for |=: 'str' and 'bool' message when trying to run script 

我在下面包含了我的代码和 json 格式的示例 .txt 文件。

示例 JSON 格式文件

{
    "detected_referrer_samples": [
        {
            "positives": 1,
            "sha256": "325f928105efb4c227be1a83fb3d0634ec5903bdfce2c3580ad113fc0f15373c",
            "total": 52
        },
        {
            "positives": 20,
            "sha256": "48d85943ea9cdd1e480d73556e94d8438c1b2a8a30238dff2c52dd7f5c047435",
            "total": 53
        }
    ],
    "detected_urls": [],
    "domain_siblings": [],
    "resolutions": [],
    "response_code": 1,
    "verbose_msg": "Domain found in dataset",
    "whois": null
}

完整追溯

Traceback (most recent call last):
  File "C:/virustotal_reporter.py", line 47, in <module>
    vt_result_check(path)
  File "C:/virustotal_reporter.py", line 22, in vt_result_check
    vt_result |= any(sample['positives'] > 0 for sample_type in sample_types
TypeError: unsupported operand type(s) for |=: 'str' and 'bool'

代码

import os
import json
import csv

path="C:/Users/bwerner/Documents/output/"


def vt_result_check(path):
    vt_result = False
    for filename in os.listdir(path):
        with open(path + filename, 'r') as vt_result_file:
            vt_data = json.load(vt_result_file)

        l = ()

        # Look for any positive detected referrer samples
        # Look for any positive detected communicating samples
        # Look for any positive detected downloaded samples
        # Look for any positive detected URLs
        sample_types = ('detected_referrer_samples', 'detected_communicating_samples',
                        'detected_downloaded_samples', 'detected_urls')
        vt_result |= any(sample['positives'] > 0 for sample_type in sample_types
                                                 for sample in vt_data.get(sample_type, []))

        # Look for a Dr. Web category of known infection source
        vt_result |= vt_data.get('Dr.Web category') == "known infection source"

        # Look for a Forecepoint ThreatSeeker category of elevated exposure
        # Look for a Forecepoint ThreatSeeker category of phishing and other frauds
        # Look for a Forecepoint ThreatSeeker category of suspicious content
        threats = ("elevated exposure", "phishing and other frauds", "suspicious content")
        vt_result |= vt_data.get('Forcepoint ThreatSeeker category') in threats

        vt_result = str(vt_result)
        print(vt_result)
#        with open('output.csv', 'w') as outfile:
#            outfile.write(vt_result)
#        print(vt_result_check(path))

        #f.writerow(vt_result_check(path))

#        l.append(vt_result)

    return vt_result

if __name__ == '__main__':
    vt_result_check(path)
#    for i in range(vt_result_check(path)):

【问题讨论】:

  • 能否包含异常的完整回溯?
  • @glibdud 感谢您的评论!我刚刚添加了完整的 Traceback。非常感谢您的帮助!
  • 你在循环结束时做vt_result = str(vt_result),所以当下一个循环开始时vt_result是一个字符串。我怀疑您可能想在循环内移动vt_result = False 行。

标签: python json python-3.x


【解决方案1】:

您将vt_result 转换为字符串:

vt_result = str(vt_result)

在内循环的第一次迭代中这不是问题,但在第二次迭代中,值没有重置,您尝试在字符串上执行|=(“True”或“False”)和一个布尔值,它失败了。

你可以通过移动来解决这个问题

vt_result = False

下面

for filename in os.listdir(path):

如果这不可行,因为您需要继续使用以前迭代的值,只需删除转换行:print 打印一个布尔值就好了。

【讨论】:

  • 感谢您的帮助!现在让它工作了。我现在正在尝试将结果写入 csv 文件,但出现新错误。这是我用来写入 csv 的代码: with open('output.csv', 'w') as outfile: outfile.write('%s, %s, \n', (filename), ( vt_result), (i+1)) 我收到一条新的 TypeError 消息:TypeError: not all arguments convert during string formatting
  • 好吧,你没有使用任何字符串格式。试试outfile.write('%s, %s, %s\n' % ( (filename), (vt_result), (i+1))),或者更好的是outfile.write(f'{filename}, {vt_result}, {i+1}\n')
  • 感谢您的帮助!我试过了,我收到一条错误消息:我没有定义。我会在我的 for 循环中定义它吗?
  • @bedford 请避免提出与原始问题无关的后续问题。如果您在解决最初的问题后遇到新问题,最好在新问题中处理(当然,在尝试自己解决之后)。
【解决方案2】:

错误表明在给定的行上,|= 运算符两侧的值与该操作的类型不兼容;一个是str,另一个是bool|= 之后的表达式应始终计算为bool,因此您需要找到vt_result 变成str 的位置。而且你明确地让它更远一点:

vt_result = str(vt_result)

所以下次通过 for 循环之后,当您再次运行 vt_result |= ... 行时,您会收到错误。

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 1970-01-01
    • 2020-11-28
    • 2018-11-30
    • 2017-05-27
    • 2021-06-18
    • 2021-03-03
    • 2014-06-15
    • 2019-04-08
    相关资源
    最近更新 更多