循环无效-字符串(Python) [英] Loops not working - Strings (Python)

查看:91
本文介绍了循环无效-字符串(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读这些文本文件时我需要帮助,以某种方式,当我执行递归循环时,另一个循环总是会重置为第一行.

I need help in reading these textfiles, somehow when i do a recursive loop, the other loop always gets reset to the 1st line.

import sys
import codecs # there are actually more utf-8 char to the lines, so i needed codecs
reload(sys)
sys.setdefaultencoding('utf-8')

reader = codecs.open("txtfile1", 'r', 'utf-8')
reader2 = codecs.open("txtfile2", 'r', 'utf-8')

for row in reader:
    print row[0:11] # here the outer loops is running the cycles
    for row2 in reader2:
        print row[0:11] # here the outer loops gets resets
        if row[0:11]==row2[0:11]:
            print row[12:] + row2[12:]

文本文件如下:

txtfile1

95032302317 foo
95032302318 bar
95032302319 bron
95032302320 cow
95032302321 how 
95032302322 now
95032303001 lala
95032303002 lili

txtfile2

95032103318 bar (in another utf8 language)
95032103319 bron (in another utf8 language)
95032103320 cow (in another utf8 language)
95032103321 how (in another utf8 language)
95032103322 now (in another utf8 language)
95032103323 didi
95032103324 dada
95032103325 kaka

推荐答案

无法告诉您原因,但是可以通过简单地将for row in reader:替换为for row in reader.readlines():来解决.如果不能一次导入所有内容,则可能需要手动处理迭代.

Can't tell you why but this can be fixed by simply replacing for row in reader: with for row in reader.readlines():. If everything can't be imported at once, then you'll probably need to handle iteration manually.

我刚刚意识到我在使此工作上做了些不同的事情:

I just realized I did something slightly different in getting this to work:

outer = codecs.open(<outer loop file).readlines()
inner = codecs.open(<inner loop file).readlines()

for o in outer:
   for i in inner:
       print o

这篇关于循环无效-字符串(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆