【问题标题】:Counting of comparison symbols in text file文本文件中比较符号的计数
【发布时间】:2013-11-04 19:44:38
【问题描述】:

我的一项作业有问题。

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

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

我的代码:

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))

【问题讨论】:

    标签: python file python-3.x counter


    【解决方案1】:

    试试这个:

    c1 = Counter('hello there')
    

    然后试试这个:

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

    注意区别?当Counter 被输入一个字符串时,它会计算字符。如果您希望它计算单个字符以外的标记,则需要将您的字符串 split 转换为 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      相关资源
      最近更新 更多