读取/计算行中的字符?

时间:2012-07-30 19:27:07

标签: python count character

我正在尝试读取/计算文件中的字符(位于第2行)

该文件的所有偶数行看起来都与此类似:

--------------- LL --- NE - HVKTHTEEK --- PF-ICTVCR-KS ----------

这是我的代码到目前为止,但我得到错误说:

表示len [(line2)]中的字符: TypeError:'builtin_function_or_method'对象不可订阅

 with open(filename) as f:
    for line, line2 in itertools.izip_longest(f, f, fillvalue=''):
        tokenizer=line.split()
        print line, line2
        print tokenizer[4]
        for character in len[(line2)]:
           print 't'

2 个答案:

答案 0 :(得分:0)

问题是len是内置函数(len(mystring)返回一个整数,它是字符串中的字符数)。你不能下标它(即使用方括号将导致你在问题中引用的TypeError)。我不太确定你在这里想做什么,也许你想要:

 for character in line2:
     print character

或者你想要:

 for i,character in enumerate(line2):
     print i,character

从评论中,我仍然很难找到你想要的东西,但我想你可能会想要这样的东西:

tokenizer = line.replace('-',' ').split()[4]
idx = line.index(tokenizer)
count = line[:idx].count('-')

答案 1 :(得分:0)

line2是一个字符串,len(line2)是一个整数(line2中的字符数)。方括号用于索引(或切片)序列,例如,您可以使用line2获取line2[0]的第一个字符,或使用line2[-1]获取最后一个字符。

len内置函数不是一个序列,这就是为什么在它导致你看到错误后使用方括号。

您可以使用for循环进行迭代,但是您必须遍历可迭代的内容。你不能迭代一个整数,所以for character in len(line2):也会失败。

请改用以下方法之一:

# loop over each character in the string
for character in line2:
    ...

# loop over [0, 1, ..., len(line2)-1]
for i in range(len(line2)):
    ...

# combination of above methods, i will be the index of character in the string
for i, character in enumerate(line2):
    ...
相关问题