首页 > 解决方案 > 在文本文件中搜索。错误:“str”对象不可调用

问题描述

对不起,我在 Python 中很新。尝试使用正则表达式从文本文件中打印包含子字符串“error”的所有行。遇到类型错误,有什么建议吗?

import re
errors = []
linenum = 0
pattern = re.compile("error", re.IGNORECASE)  # Compile a case-insensitive regex
with open ('Setup.log', 'rt') as myfile:    
    for line in myfile:
        linenum += 1
        if pattern.search(line) != None:      # If a match is found 
            errors.append((linenum, line.rstrip('\n')))
for err in errors:                            # Iterate over the list of tuples
    print("Line " + str(err[0]) + ": " + err[1]) 
TypeError                                 Traceback (most recent call last)
<ipython-input-72-efb36dfad1d6> in <module>()
      9             errors.append((linenum, line.rstrip('\n')))
     10 for err in errors:                            # Iterate over the list of tuples
---> 11     print("Line " + str(err[0]) + ": " + err[1])

TypeError: 'str' object is not callable

标签: pythonstringtexttypeerror

解决方案


用作str 变量以在上方某处保存字符串。只需要重命名变量


推荐阅读