首页 > 解决方案 > seek() 函数在嵌套循环中不起作用

问题描述

我正在为缩写构建一个自定义“翻译器”。它应该接受一个字符串输入,将其拆分为单个单词并将每个单词作为缩写返回。

例子: Input: above and aloft Returns: abv & alft

缩写词是从 txt 文件中检索的,其中缩写词和关键短语由制表符分隔。每对在单独的行上。

    import csv

# Used to lowercase the library
file = open('lib.txt', 'r')

lines = [line.lower() for line in file]
with open('lib.txt', 'w') as out:
     out.writelines(sorted(lines))

# Get user input
eng = input("Plain english input:")

# Split input into separate words
words = eng.split()

# Search every word in the file, return the first word (abbreviation) in the respective line
with open('lib.txt', newline='') as lib:
    lib_reader = csv.reader(lib, delimiter='\t')
    lib.seek(0)
    print(words)
    for x in words:
        print('1')
        lib.seek(0)
        for lib in lib_reader:
            print('2')
            if x in lib:
                print(lib[0])
                break


无论出于何种原因,它运行良好,找到第一个单词,中断,回到第一个循环并在 lib.seek(0) 上给出错误。

AttributeError: 'list' object has no attribute 'seek'

据我了解,它必须将光标重置到文件中文本的开头才能开始搜索第二个单词。seek() 是为了防止它退出循环并继续搜索下一个参数。

标签: pythonfor-loopseek

解决方案


我想也许你在两件事上使用相同的变量。该冲突将lib文件句柄替换为lib来自 csv 阅读器的行,该行是一个列表。这就是您收到该错误的原因,因为该列表没有seek方法。

尝试使用lib_row而不是liblib_reader.

Python 没有块作用域,因此for循环中的变量与函数中的变量相同。

        for lib_row in lib_reader:
            print('2')
            if x in lib_row:
                print(lib_row[0])
                break

推荐阅读