【问题标题】:Python else not working correctly [duplicate]Python否则无法正常工作[重复]
【发布时间】:2018-11-11 01:57:29
【问题描述】:

我正在编写 python 脚本来计算某些字符串出现的次数,但似乎 else 无法正常工作。

这是我的代码:

import os

user_input = "#"
directory = os.listdir(user_input)

searchstring1 = 'type="entity"'

searchstring2 = 'type="field"'

searchstring3 = 'type="other"'

searchstring4 = "type="

count_entity = 0

count_field = 0

count_other = 0

count_none = 0

counttotal = 0

for fname in directory:
    if os.path.isfile(user_input + os.sep + fname):
        f = open(user_input + os.sep + fname, 'r', encoding="utf-8")
        for line in f:
            if "<noun" in line:
                counttotal += 1
                if searchstring1 in line:
                    count_entity += 1
                if searchstring2 in line:
                    count_field += 1
                if searchstring3 in line:
                    count_other += 1
                else:
                    count_none += 1

        f.close()

print("Entity Number" + str(count_entity))
print("Field Number" + str(count_field))
print("Other Number" + str(count_other))
print("None Number" + str(count_none))

如果它工作正常,count_none 应该等于 total-entity-field-other。但我不知道为什么结果 count_none = counttotal 这么明显 else 不能正常工作。

谁能告诉我为什么会这样?谢谢你的帮助!!

【问题讨论】:

  • 对除第一个 if 之外的所有内容使用 elif

标签: python python-3.x if-statement


【解决方案1】:

您的else 仅适用于前面的if(以及附加的任何elifs)。通过这样做:

            if searchstring1 in line:
                count_entity += 1
            if searchstring2 in line:
                count_field += 1
            if searchstring3 in line:
                count_other += 1
            else:
                count_none += 1

每次searchstring3 不在line 中时,您都会增加count_none,即使searchstring1searchstring2 在行中(所以count_other + count_none 的总和总是count_total)。

要解决此问题,请在if 语句之间使用elif 而不是if,因此else 的情况仅在没有 找到搜索字符串时执行: p>

            if searchstring1 in line:
                count_entity += 1
            elif searchstring2 in line:  # Changed to elif
                count_field += 1
            elif searchstring3 in line:  # Changed to elif
                count_other += 1
            else:
                count_none += 1

如果找到searchstring1,这将阻止您检查searchstring2searchstring3(同样,如果找到searchstring2,您将不会根据searchstring3 检查或增加)。如果您需要搜索所有三个,但仅在没有命中的情况下增加 count_none,您需要变得更复杂一些:

            foundany = False
            if searchstring1 in line:
                foundany = True
                count_entity += 1
            if searchstring2 in line:
                foundany = True
                count_field += 1
            if searchstring3 in line:
                foundany = True
                count_other += 1
            if not foundany:
                count_none += 1

【讨论】:

  • 非常感谢您的完美回答!
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
相关资源
最近更新 更多