【问题标题】:python TypeError: str object is not an iteratorpython TypeError:str对象不是迭代器
【发布时间】:2014-10-25 12:03:21
【问题描述】:

我正在编写一个在文本文件中搜索值并打印上一行的代码; 但我遇到了两个问题,首先我没有找到打印上一行的方法,当我编写代码打印下一个值时出现错误。

代码:-

with open('Perfix/prefix.txt') as f:
    lines = f.readlines()
    for line in lines:
        if "100" in line:
            print (next(line))

假设场景:-

代码应该在 prefix.txt 文件中搜索以找到值 100 的行,然后它应该打印上一行。就这样!!

错误:-

Traceback (most recent call last):
  File "1.py", line 7, in <module>
    print next(line)
TypeError: str object is not an iterator

什么是错误?另外,您能否建议如何打印“上一行”而不是下一行?

示例:-

文件前缀.txt

00
122
141
1525
1162
1547
100
125
15321
1100
1513
142100

输出:-

1547

【问题讨论】:

  • 您期望会发生什么?你为什么在这里使用next()
  • 跟踪前一行,如果行中有 100 则打印它

标签: python string search printing


【解决方案1】:

查找前一行的最简单方法是在每次不匹配时存储该行:

with open('Perfix/prefix.txt') as f:
    previous = None
    for line in f:
        line = line.strip()
        if line == '100':
            print previous
        previous = line

请注意,您不需要先将所有行读入内存;只需遍历文件对象。

next() 函数根本不应该在这里使用;它需要一个迭代器,并将其推进到下一个项,而不是将其倒回到上一个条目。

【讨论】:

    【解决方案2】:

    错误消息很清楚 - linestring,而不是迭代器,因此 next(line) 没有意义。考虑:

    next('hello')
    

    应该发生什么?


    为了解决您的问题,我建议如下:

    for index, line in enumerate(lines): # get the index for each line as we go
        if index and line.strip() == '100': # if this isn't the first line & is just '100'
            print lines[index-1] # print the previous line
            break # optional - stop iterating if you don't want to find further lines
    

    或成对遍历行;参见例如Iterate a list as pair (current, next) in Python.

    另请注意,您可以在文件关闭后执行此操作:

     with open(...) as f:
         lines = f.readlines()
     for index, line in enumerate(lines):
         ...
    

    【讨论】:

    • thx 兄弟,您的代码正在运行,但是当我使用它时,当文件有一个像“015100”这样的字符串时,它也被包含在内,我只需要第一个完全匹配......
    • 你是什么意思“完全匹配”?你为什么使用in?你的意思是line == '100\n'
    • @MohammedAldaoudi:您确实需要在您的问题中告诉我们您要做什么,而不仅仅是询问您不理解的错误。
    • 对不起,你可以看到我想要代码做的假设场景,请检查编辑
    【解决方案3】:

    通过re 模块。

    #!/usr/bin/python
    import re
    with open('file', 'r') as f:
        lines = f.read()
        print re.findall(r'(?m)^(.*)\n100$', lines)[0]
    

    输出:

    1547
    

    说明:

    (?m)                     set flags for this block (with ^ and $
                             matching start and end of line) (case-
                             sensitive) (with . not matching \n)
                             (matching whitespace and # normally)
    ^                        the beginning of a "line"
    (                        group and capture to \1:
      .*                       any character except \n (0 or more
                               times)
    )                        end of \1
    \n                       '\n' (newline)
    100                      '100'
    $                        before an optional \n, and the end of a
                             "line"
    

    【讨论】:

    • 这里的正则表达式太过分了,需要将整个文件读入内存。如果文件足够大,则无法执行此操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2014-04-26
    相关资源
    最近更新 更多