【发布时间】: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