Python脚本打印两次

时间:2014-07-10 16:31:53

标签: python-2.7 utf-8

这是一个小小的' hackety'脚本我写的是为了工作,它打印了两次找到的所有行,为什么?

#!/usr/bin/python

ins = open("FileName")

for line in ins:
    s  = list(line.decode("utf-8"))
    for character in s:
       if ord( character ) > 10000:
          print repr(line)

ins.close()

1 个答案:

答案 0 :(得分:3)

你的内循环需要休息。

for line in ins:
    s  = list(line.decode("utf-8"))
    for character in s:
       if ord( character ) > 10000:
          print repr(line)
          # Found it in the line, move onto the next line
          break

否则,如果一行中有多个匹配项,您将多次打印一行。

您应该对文件句柄使用 with 语句。

with open("FileName", "r") as ins:
    <do stuff with ins>

此外,您不必将line.decode()返回的字符串转换为列表;调用它的迭代器是列表构造函数无论如何都会做的。也可以摆脱中间人。

相关问题