Python else not working correctly
本问题已经有最佳答案,请猛点这里访问。
我正在编写python脚本来计算某些字符串出现的次数,但看起来似乎没有正常工作。
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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这么明显,否则无法正常工作。
谁能告诉我为什么会这样? 谢谢你的帮助!!
您的
1 2 3 4 5 6 7 8 | 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 |
每当
要修复,请在
1 2 3 4 5 6 7 8 | 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 |
如果找到
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |