0

我的一项任务有问题。

如果它需要一个文本文件并计算其中的比较符号,我应该编写一个代码。

问题是它不会打印 '=='、'>=' 或 '<='

我的代码:

from collections import Counter

chars = ['==', '>=', '<=', '<', '>']
file = open(input('specify a file'))
character_distr = Counter()

for line in file:
    character_distr += Counter(line.lower())

print('Distribution of characters: ')
for char, count in sorted(character_distr.items()):
    if char in chars:
    print('{}  :  {}'.format(char, count))
4

1 回答 1

1

尝试这个:

c1 = Counter('hello there')

然后试试这个:

c2 = Counter('hello there'.split())

注意区别?当 aCounter被输入一个字符串时,它会计算characters。如果您希望它计算除单个字符之外的标记,则需要将split您的字符串转换为 a 。list

因此,如果您的操作员之间有方便的空间,请添加.split()line.lower()那里。如果没有(这当然是合法的),您需要使用词法分析器或(更有可能)正则表达式变得更复杂。

import re
expression = 'if x>4: do_thing(); elif x==12: other_thing = x'

len(re.findall(r'==|>=|<=|<|>',expression))
Out[12]: 2
于 2013-11-04T20:12:55.780 回答